In C++, what does a new-expression do beyond calling operator new, and what happens if the constructor throws?
answer
- new-expression versus operator new
- allocate, then construct
- destroy, then deallocate
- matching deallocation on a throw
basics
~20 sA new-expression calls an allocation function (operator new) to get raw storage, then constructs the object there. If the constructor throws, the matching deallocation function frees the storage and the exception propagates; no destructor runs.
solid answer
~30 s`new Texture(64)` is a *new-expression*, a language construct; `operator new` is just the allocation function it calls. The expression looks up `operator new` - a class-specific `Texture::operator new` first, then the global one - asks it for `sizeof(Texture)` bytes, then initializes the object in that storage. `delete p` mirrors it: run `~Texture()`, then call `operator delete`. If the constructor throws, the object never existed, so no destructor runs, but the expression itself calls the **matching** deallocation function to free the storage before the exception propagates - no leak. Calling `::operator new(sizeof(T))` directly gives raw memory with no object in it.
code
cpp · 29 lines#include <cstdio>
#include <new>
#include <stdexcept>
struct Texture {
explicit Texture(int w) { if (w <= 0) throw std::invalid_argument("width"); }
~Texture() { std::puts("~Texture"); }
// Class-specific allocation functions: used by new Texture / delete p.
static void* operator new(std::size_t n) {
std::printf("Texture::operator new(%zu)\n", n);
return ::operator new(n);
}
static void operator delete(void* p) noexcept {
std::puts("Texture::operator delete");
::operator delete(p);
}
int width = 0;
};
int main() {
Texture* ok = new Texture(64); // 1. allocate 2. construct
delete ok; // 1. destroy 2. deallocate
try {
new Texture(0); // constructor throws: memory is freed, no destructor
} catch (const std::invalid_argument& e) {
std::printf("caught: %s\n", e.what());
}
}go deeper
Recall the two steps of new - allocate, then construct - and of delete - destroy, then free - and that operator new only allocates.
Explain class-scope lookup for operator new, ::new to bypass it, and why a throwing constructor triggers the matching deallocation instead of the destructor.
Trace allocation counts that change with optimization because calls to replaceable allocation functions may be omitted, and spot leaks from allocating before ownership is taken.
Decide where class-specific allocation functions belong - pools for hot small types - and keep raw new-expressions out of ordinary code.
## Two different things called "new" Interviewers like this distinction because the names invite confusion: | Term | What it is | What it does | |---|---|---| | **new-expression** - `new Texture(64)` | a language expression | allocates storage, then constructs the object, then yields a typed pointer | | **allocation function** - `operator new(std::size_t)` | an ordinary function you can call, replace or overload | returns raw storage of at least the requested size, or throws `std::bad_alloc` | | **delete-expression** - `delete p` | a language expression | runs the destructor, then calls the deallocation function | | **deallocation function** - `operator delete(void*)` | an ordinary function | releases raw storage | Calling `::operator new(sizeof(Texture))` yourself gives you bytes, not a `Texture`; nothing is constructed. Overloading or replacing `operator new` changes **where memory comes from**, never the construct-and-destroy steps the expressions perform. ## The steps of new T(args) 1. **Look up the allocation function.** For a class type, the name `operator new` is looked up in the class scope first; if the class declares one, it is used. Otherwise the global one is used. Writing `::new T` skips the class-specific lookup. 2. **Call it** with the required size (and, for over-aligned types since C++17, a `std::align_val_t` alignment argument). 3. **Initialize the object** in the returned storage: run the constructor for class types, or apply the initializer for others. `new int` leaves the `int` uninitialized; `new int()` value-initializes it to zero. 4. **Yield** a `T*` to the new object. The delete-expression reverses it: if the pointer is non-null, call `~T()`, then look up and call the deallocation function. If the static type has a virtual destructor, the destructor that runs - and the class-scope `operator delete` that is found - are those of the dynamic type; that is the material on virtual destructors. ## When the constructor throws If step 3 throws, the object's lifetime never began. So: - **no destructor runs** for the half-built object - members and bases that were already fully constructed are destroyed by the normal constructor rules, in reverse order; - the new-expression **calls the deallocation function that matches the allocation function it used** - for a class-specific `operator new`, the class-specific `operator delete`; for a placement form with extra arguments, the `operator delete` with the same extra arguments, if one is declared; - then the exception continues to propagate. This is why `new Texture(0)` with a throwing constructor does not leak, as the example shows: the trace prints the class-specific `operator new`, then `operator delete`, and no `~Texture`. ## Arrays: new T[n] The array form follows the same pattern with two differences: - `operator new[]` is asked for `n * sizeof(T)` bytes plus any **array allocation overhead** the implementation needs to remember `n` for `delete[]`; - elements are constructed in order from index 0. If element `k` throws, the elements `0..k-1` that were already constructed are destroyed in reverse order, the storage is freed through the matching `operator delete[]`, and the exception propagates - a run with a constructor that throws on the third element printed `T0 T1 ~T1 ~T0` before the handler. ## The allocation-before-argument trap The guarantee covers the storage of the object being constructed, nothing else. Code like `consume(std::unique_ptr<Texture>(new Texture(64)), load_settings());` was a classic leak before C++17: the compiler could allocate and construct the `Texture`, then call `load_settings()`, which throws, before the `unique_ptr` took ownership. C++17's rule that function arguments are evaluated indeterminately sequenced - one argument completes before the next starts - narrows that, and `std::make_unique` sidesteps it; the details belong to the ownership material and to the lesson on operators and sequencing. ## What the standard lets the implementation skip - An implementation **may omit a call to a replaceable global allocation function** and provide the storage itself. Clang does this at `-O2` for a `new`/`delete` pair whose pointer never escapes, which is why an allocation counter can read differently at `-O0` and `-O2`. - `delete` on a null pointer is a no-op; the deallocation function may or may not be called, which is unspecified. ## A short checklist - Distinguish the expression from the function, in those words. - List the order: allocate, construct; destroy, deallocate. - Say what happens on a throwing constructor: matching deallocation, no destructor, exception propagates. - Mention class-specific lookup and `::new` to bypass it.
- What is the difference between new int and new int() in C++?`new int` default-initializes the object, which for `int` means it has an indeterminate value; reading it before assignment is undefined behaviour. `new int()` and `new int{}` value-initialize it to zero. For class types with a user-provided default constructor both forms call that constructor.
- If a class declares its own operator new, how do you force the global one?Write `::new T(args)`. The leading `::` makes the new-expression look up `operator new` only in the global scope, skipping the class-scope lookup. Likewise `::delete p` uses the global `operator delete`. Pool-backed classes sometimes do this inside their own allocator to get the underlying blocks.
- new T and operator new(sizeof(T)) do the same thing
- If the constructor throws, the memory from new leaks
- If the constructor throws, the destructor runs to clean up
- Replacing operator new changes how objects are constructed
- delete calls operator delete first and then the destructor