September 6, 2026

The Hidden Consequences of noexcept in Modern C++

noexcept looks like a small function specifier. In production C++, it can change container behavior, generic code, callback contracts, failure handling and even compatibility assumptions.

That is why treating noexcept as an optimization hint is dangerous.

Consider a type stored inside a std::vector. Add noexcept to its move constructor and the container may start moving objects during reallocation instead of copying them. Put noexcept on an event-dispatch function and an exception escaping from a user callback no longer reaches the caller: the process terminates. Put throwing cleanup inside an ordinary destructor and you may have created the same termination path without writing noexcept anywhere.

At an API boundary, the specifier goes even further. Since C++17, the exception specification participates in the function type. Generic code can inspect it, callback types can depend on it, virtual interfaces can constrain overrides, and changing it later may affect source or binary compatibility depending on how the API is exposed.

Note

This article is not an argument for adding noexcept everywhere. The useful question is: which functions can make a durable non-throwing promise, and what changes elsewhere in the program once they do?

1 hiddenconsequencesofnoexcept

Start with the real model: noexcept is a promise


Every C++ function is either potentially throwing or non-throwing.

void readConfiguration();                 // potentially throwing

void resetHardware() noexcept;            // non-throwing

void updateCache() noexcept(false);       // potentially throwing

noexcept is equivalent to noexcept(true). It tells both the compiler and other C++ code that an exception will not escape this function.

Notice the wording: will not escape.

A noexcept function can execute code that throws, provided that it catches the exception before it leaves the function:

void pollDevice() noexcept
{
    try {
        device.poll();
    } catch (const DeviceError& error) {
        logDeviceError(error);
        markDeviceOffline();
    }
}

The contract is about the boundary. The caller is guaranteed that pollDevice() itself will not propagate an exception.

That guarantee is useful because other code can make decisions from it at compile time:

static_assert(noexcept(pollDevice()));
static_assert(std::is_nothrow_invocable_v<decltype(pollDevice)>);

The standard library does exactly this kind of reasoning. Generic code does not have to trust comments saying that an operation “normally does not throw”. It can inspect the actual exception specification.

Useful mental model

noexcept is a contract consumed by callers, generic algorithms and the runtime. Once exposed, it is no longer only an implementation detail of the function body.

Why containers care about a noexcept move constructor


This is probably the most visible performance consequence of noexcept.

Imagine a packet type owning a dynamically allocated payload:

class Packet
{
public:
    explicit Packet(std::size_t size)
        : data_(std::make_unique<std::byte[]>(size))
        , size_(size)
    {
    }

    Packet(const Packet& other)
        : Packet(other.size_)
    {
        std::copy_n(other.data_.get(), size_, data_.get());
    }

    Packet(Packet&& other)
        : data_(std::move(other.data_))
        , size_(std::exchange(other.size_, 0))
    {
    }

private:
    std::unique_ptr<std::byte[]> data_;
    std::size_t size_{};
};

The move constructor is cheap. It transfers a pointer and a size. But it is not declared noexcept.

Now put the type in a growing vector:

std::vector<Packet> queue;

queue.emplace_back(4096);
queue.emplace_back(4096);
queue.emplace_back(4096);
// Eventually vector needs a larger allocation.

When the vector reallocates, it has to construct its existing elements in new storage. Conceptually it has two choices:

  • copy each existing element;
  • move each existing element.

Moving sounds obviously better. The difficulty is exception safety.

Suppose the vector has already moved twenty elements into its new allocation and the twenty-first move throws. The first twenty objects in the old allocation may already be moved-from. Simply discarding the new storage no longer restores the original vector state.

A copy operation is different. If copying element twenty-one throws, the original twenty-one elements have not been modified. The container can destroy the partial copies in the new allocation and keep the original vector intact.

This is why the standard library uses the same idea exposed by std::move_if_noexcept: prefer moving when moving is known not to throw, otherwise preserve copying as the safer option when copying is available.

Move constructorCopy available?Useful relocation strategyReason
noexceptYesMoveCheap relocation without risking partially moved original state
May throwYesOften copyAllows the strong exception guarantee to be preserved
May throwNoMust moveThere is no copy fallback; exception guarantees become weaker if the move throws
2 hiddenconsequencesofnoexcept

One keyword can turn vector copies into moves


For the packet type above, the move really is non-throwing. Its members already support non-throwing moves. The correct declaration is:

Packet(Packet&& other) noexcept
    : data_(std::move(other.data_))
    , size_(std::exchange(other.size_, 0))
{
}

Now generic code can see the guarantee:

static_assert(
    std::is_nothrow_move_constructible_v<Packet>);

For a type that owns a large buffer, a file-descriptor wrapper, protocol state or another expensive-to-copy resource, this distinction can be significant.

The useful lesson is not “always put noexcept on move constructors”. The useful lesson is:

Production recommendation

If moving your type genuinely cannot fail, make that visible. Standard containers and generic algorithms can use the stronger guarantee.

There is also a simpler option when the compiler can correctly derive the guarantee for you:

class Packet
{
public:
    Packet(Packet&&) = default;
    Packet& operator=(Packet&&) = default;

private:
    std::unique_ptr<std::byte[]> data_;
    std::size_t size_{};
};

A defaulted move operation gets an exception specification derived from the operations required to move its bases and members. If all those operations are non-throwing, the generated move can be non-throwing too.

Common mistake

Do not manually write noexcept only to make std::vector move your type. First make sure every operation executed by that move constructor can really satisfy the promise.

What happens when a noexcept function actually throws?


The answer is not “the exception is ignored”. It is not converted into an error code either.

If an exception attempts to leave a non-throwing function, the runtime calls std::terminate().

void sendHeartbeat() noexcept
{
    transport.send("heartbeat"); // may throw TransportError
}

void run()
{
    try {
        sendHeartbeat();
    } catch (const TransportError&) {
        recoverTransport(); // this will not catch an exception
                           // that escapes sendHeartbeat()
    }
}

If transport.send() throws and sendHeartbeat() does not catch it internally, the outer catch is not the recovery path. The program terminates when the exception crosses the noexcept boundary.

This matters especially when someone adds noexcept during a cleanup pass because the function “doesn’t normally throw”.

Imagine that six months later the implementation gains logging, allocation, a callback, a filesystem operation or another dependency that can throw. The declaration may continue compiling perfectly. The failure mode has simply changed from exception propagation to process termination.

Important

noexcept does not prove that the implementation contains no throwing operations. It defines what must happen if an exception escapes despite the promise.

3 hiddenconsequencesofnoexcept

Termination is a very different operational contract


For an embedded Linux daemon, process termination may trigger an entire operational chain:

  • the process exits abruptly;
  • systemd records the failure;
  • a configured restart policy may launch the daemon again;
  • in-flight state may be lost;
  • a partially completed external operation may need recovery;
  • the original exception may become visible only through the generated core dump or whatever diagnostics were written before termination.

That may be acceptable for a violated internal invariant or for a boundary where recovery is impossible. It is a poor substitute for normal error handling.

If a connection timeout, configuration problem or transient device error is a normal production condition, do not turn it into termination simply because the surrounding function was marked noexcept.

Make terminate failures diagnosable


A noexcept violation often looks like a mysterious abort when the only visible symptom is that the process disappeared.

During development, a small terminate handler can at least make the boundary visible:

#include <cstdio>
#include <cstdlib>
#include <exception>

int main()
{
    std::set_terminate([] {
        std::fputs(
            "fatal: std::terminate called\n",
            stderr);

        std::abort();
    });

    runApplication();
}

In production, the more useful artifact is normally a stack trace or core dump showing which non-throwing boundary was being crossed.

On a development system with systemd-coredump available, a useful flow is:

coredumpctl list device-daemon
coredumpctl info device-daemon
coredumpctl gdb device-daemon

Then inspect the backtrace at the point where the runtime entered termination. Keep debug symbols for production builds somewhere accessible to your crash-analysis pipeline, even when the deployed binary itself is stripped.

Debugging question

When you see an unexpected abort() or std::terminate(), search the stack not only for the throw site. Look for the nearest destructor, callback wrapper, move operation or public function whose exception specification forbids the exception from escaping.

Conditional noexcept keeps generic promises honest


Templates often cannot promise unconditionally that they will not throw. Their behaviour depends on operations supplied by the template arguments.

Consider a generic invocation wrapper:

template <typename F, typename... Args>
decltype(auto) invokeForward(
    F&& function,
    Args&&... args)
    noexcept(
        noexcept(
            std::invoke(
                std::forward<F>(function),
                std::forward<Args>(args)...)))
{
    return std::invoke(
        std::forward<F>(function),
        std::forward<Args>(args)...);
}

The inner noexcept(...) is an operator. It asks at compile time whether the expression is known not to throw.

The outer noexcept(...) is the function’s exception specification.

The result is a useful forwarding contract:

  • if invoking the supplied callable is non-throwing, the wrapper is non-throwing;
  • if invoking it can throw, the wrapper remains potentially throwing.

The same idea can be written using type traits:

template <typename F, typename... Args>
decltype(auto) invokeForward(
    F&& function,
    Args&&... args)
    noexcept(
        std::is_nothrow_invocable_v<F, Args...>)
{
    return std::invoke(
        std::forward<F>(function),
        std::forward<Args>(args)...);
}

This is where conditional noexcept is most useful: generic infrastructure whose own guarantee should accurately mirror the operations it delegates to.

4 hiddenconsequencesofnoexcept

Do not over-engineer conditional noexcept


Conditional specifications are powerful, but they can also turn declarations into unreadable template machinery.

If a special member function can simply be defaulted, prefer letting the compiler derive its exception specification:

class Connection
{
public:
    Connection(Connection&&) = default;
    Connection& operator=(Connection&&) = default;

private:
    Socket socket_;
    std::string endpoint_;
};

If both members can be moved without throwing, the generated move constructor can reflect that. If a member later changes to a potentially throwing move, the generated specification changes with the real implementation.

Compare that with manually forcing the promise:

Connection(Connection&& other) noexcept
    : socket_(std::move(other.socket_))
    , endpoint_(std::move(other.endpoint_))
{
}

This may be correct today. But now the declaration has to remain correct after every future member change.

Prefer derived guarantees where possible

For defaulted special members, let the language derive the exception specification. Write an explicit noexcept when you are deliberately establishing a stronger public contract.

Destructors are already part of the noexcept story


One of the more surprising consequences is that you can create a non-throwing boundary without explicitly writing noexcept.

Destructors are normally non-throwing by default. An implicitly declared destructor is non-throwing unless one of the relevant base or member destructors is potentially throwing.

A user-written destructor normally inherits the same expectation unless you deliberately give it a potentially throwing exception specification.

This makes code like the following dangerous:

class Session
{
public:
    ~Session()
    {
        persistState(); // may throw std::filesystem_error
    }

private:
    void persistState();
};

If persistState() throws out of this destructor, the program may terminate because the destructor’s exception specification is non-throwing.

Making the destructor explicitly throwing is usually not the solution:

~Session() noexcept(false);

A destructor that throws while another exception is already unwinding the stack leads to termination anyway. More importantly, callers cannot reliably react to errors reported from automatic cleanup because destruction happens in many contexts.

Do not hide important failure inside a destructor


Suppose a transaction object must write state to flash or commit data to a database. If failure matters to the caller, make the operation explicit:

class Transaction
{
public:
    std::expected<void, CommitError> commit();

    ~Transaction() noexcept
    {
        if (!committed_) {
            rollbackNoThrow();
        }
    }

private:
    void rollbackNoThrow() noexcept;

    bool committed_{false};
};

Now the important operation has a normal error channel:

auto result = transaction.commit();

if (!result) {
    reportCommitFailure(result.error());
    return;
}

The destructor handles cleanup that must not fail outwardly. The caller handles the operation whose failure changes application behaviour.

Common failure mode

A destructor that performs “one last important operation” can silently turn a recoverable storage, logging or IPC error into process termination. If the caller needs the result, expose an explicit operation before destruction.

5 hiddenconsequencesofnoexcept

Callback boundaries are where noexcept becomes especially dangerous


Callbacks combine two independent contracts: who owns control flow and who owns failure handling.

Consider an event dispatcher:

class EventDispatcher
{
public:
    using Handler =
        std::function<void(const Event&)>;

    void setHandler(Handler handler)
    {
        handler_ = std::move(handler);
    }

    void dispatch(const Event& event) noexcept
    {
        if (handler_) {
            handler_(event);
        }
    }

private:
    Handler handler_;
};

The dispatcher claims that dispatch() never throws. The callback type makes no such promise.

That mismatch is now a hidden process-termination path:

dispatcher.setHandler([](const Event& event) {
    persist(event); // may throw
});

dispatcher.dispatch(event);

If persist() throws, the exception exits the lambda, exits the std::function call and attempts to leave dispatch(). The runtime terminates the process.

There are three reasonable designs. Pick one deliberately.

Option 1: allow the callback exception to propagate

void dispatch(const Event& event)
{
    if (handler_) {
        handler_(event);
    }
}

This can be correct for synchronous library code where the caller owns the exception policy.

Option 2: contain callback failures at the boundary

void dispatch(const Event& event) noexcept
{
    if (!handler_) {
        return;
    }

    try {
        handler_(event);
    } catch (const std::exception& error) {
        logCallbackFailure(error.what());
    } catch (...) {
        logUnknownCallbackFailure();
    }
}

This can make sense for an event loop or plugin boundary where one callback is not allowed to unwind through the infrastructure.

But catching the exception is only half the design. Decide what happens next. Disable the handler? Mark the component failed? Drop one event? Restart a subsystem? Continuing blindly after an arbitrary exception can be as dangerous as terminating.

Option 3: require a non-throwing callback

For a template boundary, you can express that requirement using a type trait:

template <typename Callback>
requires std::is_nothrow_invocable_v<
    Callback&,
    const Event&>
void dispatch(
    const Event& event,
    Callback&& callback) noexcept
{
    std::invoke(callback, event);
}

The compilation fails if the callable cannot satisfy the non-throwing contract.

For an owning runtime callback in C++23, std::move_only_function can even carry the exception specification in its signature:

using Handler =
    std::move_only_function<
        void(const Event&) noexcept>;

That is materially different from std::function<void(const Event&)>, which does not express that the stored callback must be non-throwing.

Callback rule

Do not put an unconstrained callback behind a noexcept boundary and assume callers will know not to throw. Either propagate, contain, or encode the callback’s non-throwing requirement.

6 hiddenconsequencesofnoexcept

Public APIs should promise noexcept selectively


There is a large difference between adding noexcept to a private helper and adding it to a public SDK or library interface.

A public declaration makes a promise that consumers may build into their own code:

class Connection
{
public:
    bool isOpen() const noexcept;
    void close() noexcept;
};

Consumers can now use those functions in conditional noexcept expressions, static assertions, generic algorithms and their own non-throwing functions.

That is useful if the guarantee is fundamental to the abstraction.

For example, querying a cached state flag can usually make a durable non-throwing promise:

bool isOpen() const noexcept
{
    return state_ == State::Open;
}

But close() deserves more thought.

Does closing only reset local handles? Does it flush a protocol queue? Does it perform TLS shutdown? Does it persist state? Can a plugin participate? Could future implementation requirements make failure useful to the caller?

If the API needs to report meaningful close failures later, an early unconditional noexcept promise becomes a constraint.

API design warning

Do not add noexcept to a public function only because today’s implementation happens not to throw. Add it when non-throwing behaviour is part of the abstraction you are prepared to preserve.

Virtual interfaces make the promise even stronger


Consider an interface used by a low-level event loop:

class IEventSink
{
public:
    virtual ~IEventSink() = default;

    virtual void onEvent(
        const Event& event) noexcept = 0;
};

A derived implementation cannot weaken that contract by exposing a potentially throwing override:

class LoggingSink : public IEventSink
{
public:
    void onEvent(
        const Event& event) override; // invalid: weaker exception contract
};

The interface author has therefore made a system-wide design decision: every implementation must keep exceptions inside the callback boundary.

That can be exactly right for interrupt-adjacent dispatch, C ABI adapters, destructors, scheduler internals or other infrastructure where unwinding through the boundary is forbidden.

It is a much stronger choice than adding a convenience annotation.

Changing noexcept later can affect compatibility


This is where noexcept becomes relevant to library maintenance.

Since C++17, the exception specification is part of the function type.

using MayThrow = void (*)();
using NoThrow = void (*)() noexcept;

void safeCallback() noexcept;
void regularCallback();

MayThrow a = &safeCallback;    // OK
NoThrow b = &safeCallback;     // OK

MayThrow c = &regularCallback; // OK
// NoThrow d = &regularCallback; // error

A pointer to a non-throwing function can be converted to the more permissive potentially throwing function-pointer type. The reverse conversion is not allowed.

This means changing an API’s exception specification can alter:

  • template argument deduction;
  • the result of std::is_nothrow_invocable and related traits;
  • which callback/function-pointer conversions are valid;
  • whether a derived virtual function is a valid override;
  • mangled types or template instantiations that contain function types.

Functions cannot be overloaded only by changing noexcept, but that does not mean changing it is irrelevant to compatibility.

ABI compatibility is toolchain-specific


The C++ standard defines language semantics, not the binary ABI used by your compiler and platform.

On the Itanium C++ ABI used by GCC and Clang on many Unix-like targets, adding or removing noexcept from an ordinary non-template function does not necessarily change that function’s external symbol name.

But noexcept is encoded when a function type itself appears in places such as pointer types and template instantiations. That means an API involving callback types or templated wrappers can produce different symbols.

The effect also becomes visible when code compiled in different language modes meets. C++17 made noexcept part of the function type, so template instantiations involving function pointers may differ from equivalent C++14 builds.

Library maintenance rule

Do not label a noexcept change “ABI safe” without checking the actual compiler, ABI, exported declarations and supported C++ language modes of your product.

7 hiddenconsequencesofnoexcept

Inspect compatibility instead of guessing


If you maintain a shared library or vendor SDK, inspect actual symbols when changing exception specifications.

For example:

nm -C libdevice.so | grep registerHandler

readelf -Ws libdevice.so \
  | c++filt \
  | grep registerHandler

Do this for both the old and new build and compare exported symbols.

With GCC, warnings related to exception specifications and ABI changes can also be useful during migrations. In particular, -Wnoexcept-type can expose C++17 function-type changes involving noexcept.

For a library with a documented binary-compatibility promise, symbol inspection should be part of a broader ABI check rather than a manual one-off command.

A realistic failure: adding a member breaks your move guarantee


Imagine a queue entry originally contains only types with non-throwing moves:

class QueueEntry
{
public:
    QueueEntry(QueueEntry&&) noexcept = default;

private:
    std::unique_ptr<Payload> payload_;
    std::uint32_t sequence_{};
};

Later someone adds a diagnostic object:

class QueueEntry
{
public:
    QueueEntry(QueueEntry&&) noexcept = default;

private:
    std::unique_ptr<Payload> payload_;
    std::uint32_t sequence_{};
    DiagnosticContext diagnostics_;
};

If DiagnosticContext has a potentially throwing move constructor, explicitly defaulting QueueEntry(QueueEntry&&) noexcept asks the compiler to maintain a non-throwing contract around an operation that may need to throw.

Depending on the declarations involved, this may become ill-formed or create exactly the termination behaviour you were trying to avoid.

A simple regression test is cheap:

static_assert(
    std::is_nothrow_move_constructible_v<QueueEntry>);

static_assert(
    std::is_nothrow_move_assignable_v<QueueEntry>);

If container performance or a public contract relies on non-throwing movement, make that assumption executable instead of leaving it in a comment.

Common noexcept mistakes in production code


  • Adding noexcept everywhere as an optimization. It changes failure semantics. Performance is not enough justification for a promise you cannot maintain.
  • Forgetting noexcept on a genuinely non-throwing move constructor. Containers may copy expensive objects during growth when they could safely move them.
  • Marking a move constructor noexcept only to influence std::vector. If one member move can throw, you have hidden termination behind a performance tweak.
  • Doing fallible work in a destructor. Destructors are normally non-throwing, and throwing during stack unwinding is especially dangerous.
  • Calling an unconstrained callback from a noexcept function. The callback may become a hidden terminate boundary.
  • Assuming a function does not throw because today’s code does not contain throw. Allocation, library calls, constructors, callbacks and overloaded operators may all throw indirectly.
  • Changing public noexcept declarations casually. Function types, traits, callback conversions, virtual overrides and ABI-sensitive templates may depend on them.
  • Catching everything inside a noexcept boundary and continuing blindly. Exception containment still needs a recovery policy.

Useful compile-time checks


The type system can verify many of the assumptions that matter in generic and container-heavy code.

static_assert(
    std::is_nothrow_move_constructible_v<Packet>);

static_assert(
    std::is_nothrow_move_assignable_v<Packet>);

static_assert(
    std::is_nothrow_destructible_v<Packet>);

static_assert(
    std::is_nothrow_invocable_v<
        EventHandler&,
        const Event&>);

The noexcept operator is useful when the exact expression matters:

static_assert(
    noexcept(
        std::declval<Packet&>().reset()));

These checks are particularly useful when a type is infrastructure used across many components. A member-type change can then break the build immediately instead of quietly changing vector behaviour or callback guarantees.

Review noexcept from the call site, not only the function body


During code review, it is tempting to inspect a declaration like this:

void DeviceManager::shutdown() noexcept;

and ask only:

“Can the current implementation throw?”

That question is too narrow.

Also ask:

  • Will callers build their own noexcept guarantees on top of this one?
  • Does this function invoke callbacks, plugins or user-provided behaviour?
  • Could an implementation change add allocation, I/O or another fallible operation?
  • If an unexpected exception appears, is process termination the intended operational response?
  • Is this declaration part of a public header with source or ABI compatibility requirements?
  • Would an explicit result type communicate expected failures better than exceptions or termination?

The right answer may still be noexcept. But now it is an API decision rather than decoration.

Production recommendations


  • Make genuinely non-throwing move operations visible. This helps containers preserve strong guarantees while relocating efficiently.
  • Prefer defaulted special members when they express the right semantics. Let the compiler derive conditional exception specifications from member operations.
  • Keep destructors non-throwing. Put important fallible work in explicit functions that return or throw a result the caller can handle.
  • Audit callback boundaries before marking infrastructure noexcept. Decide explicitly whether callback exceptions propagate, are contained or are forbidden by the callback type.
  • Use conditional noexcept in generic wrappers. Mirror the real guarantee of delegated operations instead of promising more than the template can know.
  • Treat public noexcept as part of the API contract. Be prepared to preserve it for consumers.
  • Regression-test assumptions with type traits. Especially for types stored in vectors and for callback abstractions that depend on non-throwing invocation.
  • Make termination observable. Preserve symbols, collect core dumps where appropriate and make sure an unexpected std::terminate can be connected back to the offending boundary.
  • Check ABI-sensitive changes on the actual toolchain. Do not infer binary compatibility from language syntax alone.
8 hiddenconsequencesofnoexcept

The key idea


If you remember only one thing, remember this:

noexcept is not a statement about what usually happens. It is a promise about what callers may rely on when something goes wrong.

For move constructors, that promise lets containers relocate objects without sacrificing exception guarantees.

For callbacks and destructors, the same promise can turn an escaping exception into immediate termination.

For generic and public APIs, the promise becomes visible to the type system and can influence downstream code and compatibility.

Use noexcept where the non-throwing guarantee is real, useful and maintainable. Then treat breaking that guarantee with the same seriousness as breaking any other API contract.