skip to content

In C++, how does new (std::nothrow) differ from plain new when allocation fails, and what does it not protect against?

level: middleimportance: should knowfreq 50%

answer

  1. exception versus null pointer
  2. std::bad_alloc from plain new
  3. the new_handler loop
  4. constructors can still throw

basics

~10 s

Plain new reports allocation failure by throwing std::bad_alloc and never returns null; new (std::nothrow) returns a null pointer instead. The nothrow form covers only allocation: a throwing constructor still throws.

solid answer

~40 s

A plain `new T` uses `operator new(std::size_t)`, which must return non-null storage or throw `std::bad_alloc` - so `if (p == nullptr)` after it is dead code. `new (std::nothrow) T` selects the `const std::nothrow_t&` overload, which returns `nullptr` on failure; the program must check it. Before failing, the default allocation functions loop calling the installed `std::new_handler` (set with `std::set_new_handler`), which can free a cache and retry. The nothrow tag changes nothing about construction: if `T`'s constructor throws, the exception propagates, after the storage is freed. Array lengths that are negative or too large make a throwing array new throw something matching `std::bad_array_new_length`, a `std::bad_alloc` subclass. Most code should let `bad_alloc` propagate; nothrow suits code that has a real fallback.

code

cpp · 30 lines
cpp
#include <cstddef>
#include <cstdio>
#include <new>
#include <stdexcept>

struct Chunk {
    explicit Chunk(bool fail) { if (fail) throw std::runtime_error("init"); }
};

int main() {
    std::size_t huge = static_cast<std::size_t>(-1) / 2;   // far beyond any heap

    char* a = new (std::nothrow) char[huge];               // failure -> nullptr
    std::printf("nothrow new[]: %s\n", a ? "got memory" : "nullptr");
    delete[] a;                                            // deleting nullptr is a no-op

    try {
        char* b = new char[huge];                          // failure -> exception
        delete[] b;
    } catch (const std::bad_alloc&) {
        std::printf("plain new[]: std::bad_alloc\n");
    }

    try {
        Chunk* c = new (std::nothrow) Chunk(true);         // nothrow covers allocation only
        delete c;
    } catch (const std::runtime_error& e) {
        std::printf("constructor still throws: %s\n", e.what());
    }
}

go deeper

for a junior

Recall that plain new throws std::bad_alloc on failure and never returns null, while new (std::nothrow) returns nullptr that you must check.

for a middle

Explain the new_handler retry loop, why nothrow covers only allocation and not the constructor, and the dead-code null check after plain new.

for a senior

Know when bad_alloc really happens - absurd sizes, limits, fixed heaps - and design recovery points instead of scattering null checks.

for a principal

Set the out-of-memory policy for a codebase: which subsystems may degrade on nothrow allocation, which let bad_alloc propagate, and how handlers release caches.

## Two failure contracts The standard library declares the allocation functions with two different contracts: | Form | Function called | On failure | Must you check for null? | |---|---|---|---| | `new T` / `new T[n]` | `operator new(std::size_t)` / `operator new[]` | throws `std::bad_alloc` | no - it never returns null | | `new (std::nothrow) T` / `new (std::nothrow) T[n]` | `operator new(std::size_t, const std::nothrow_t&) noexcept` | returns a null pointer | yes, always | The standard's own example says it in two lines: `new T` "throws bad_alloc if it fails" and `new(nothrow) T` "returns nullptr if it fails". The requirement that the throwing forms return non-null or throw is binding on replacement versions too, so a custom global `operator new` that returns `nullptr` breaks every caller. The common mistake in older code is the C habit: ```cpp Mesh* m = new Mesh; if (!m) { return nullptr; } // dead code: plain new never yields null ``` The check never fires; failure arrives as an exception instead, and the function above is not ready for it. ## The new_handler loop The default throwing `operator new` does not give up on the first failure. It runs a loop: 1. try to allocate - whether this calls `malloc` or `aligned_alloc` is unspecified; 2. on success, return the storage; 3. on failure, if no `std::new_handler` is installed, throw `std::bad_alloc`; 4. otherwise call the handler and repeat. A handler installed with `std::set_new_handler` can release memory - drop a texture cache, shrink a pool - so the retry succeeds, or it can throw `std::bad_alloc` itself or terminate. A handler that has nothing left to release must not return, or uninstall itself, because returning makes the loop try again forever: ```cpp void release_texture_cache() { if (!g_texture_cache.drop_least_recent()) // the engine's own cache std::set_new_handler(nullptr); // nothing left: next failure throws } // at startup: std::set_new_handler(release_texture_cache); ``` `std::get_new_handler` (C++11) returns the handler currently installed. The default nothrow forms call the throwing ones and return null if they exit with an exception, so they go through the same handler loop. ## What nothrow does not change - **Constructors still throw.** `new (std::nothrow) Chunk(true)` allocates successfully, the constructor throws, the storage is freed by the matching nothrow `operator delete`, and the exception propagates - the example prints `constructor still throws: init`. - **Deleting the result** uses ordinary `delete`; `delete` on a null pointer is a no-op, so `delete[] a;` after a failed nothrow allocation is safe. - **Allocations inside the object** - a `std::vector` member growing in the constructor - use plain `new` and can throw `std::bad_alloc` regardless of how the outer object was allocated. ## Array lengths that cannot work For `new T[n]` with a run-time `n`, the standard says the expression is erroneous if `n` is negative, or the size exceeds the implementation's limit. Then no allocation function is called: a nothrow array new yields null, and a throwing one throws an exception matching `std::bad_array_new_length`, which derives from `std::bad_alloc`. In a test on this machine, Apple clang 21 threw a plain `std::bad_alloc` for a negative length instead, so portable code catches `std::bad_alloc`, which covers both. ## Does any of this happen in practice? On systems that overcommit memory, a large `new` can succeed and the process is killed later when pages are touched, so `bad_alloc` is rarer than the API suggests. It still appears: - for absurd sizes - a corrupted length field, an overflow in `width * height * 4` - which fail immediately, as the example's half-of-`SIZE_MAX` request does; - under address-space limits, 32-bit processes and container memory limits configured to fail allocations; - on consoles and embedded targets with fixed heaps. ## Choosing between them - Default to plain `new` (or, better, containers and `std::make_unique`) and let `std::bad_alloc` propagate to a level that can report it. - Use `new (std::nothrow)` where there is a real fallback - a lower-resolution texture, a smaller buffer - and check every result. - Code built without exceptions changes the picture entirely; that is the material on restricted language subsets.

  • What is a new_handler and when would you install one?
    A `std::new_handler` is a `void()` function installed with `std::set_new_handler`. The default throwing `operator new` calls it each time an allocation attempt fails, then retries. A handler can free a cache so the retry succeeds, throw `std::bad_alloc`, or terminate with a diagnostic. Games and servers use it to drop reclaimable caches before failing.
  • Why is checking the result of plain new against nullptr a code smell?
    The throwing `operator new` must return non-null storage or throw `std::bad_alloc`, and the requirement binds replacement functions too, so the check can never be true. It signals that the author expects C's `malloc` contract, and the surrounding code is usually not exception-safe for the failure that actually arrives.

  • Plain new returns nullptr when memory runs out
  • new (std::nothrow) guarantees the whole expression cannot throw
  • A custom operator new may return nullptr to signal failure
  • bad_alloc can never happen on modern systems
  • The result of new (std::nothrow) can be used without a check