FAQ 12.17 In p = new Fred(), does the Fred memory "leak" if the Fred constructor throws an exception?
If an exception occurs in the Fred constructor during p = new Fred(), the sizeof(Fred) bytes that were allocated are automatically released back to the heap. This is because new Fred() is a two-step process.
Thus the compiler generates code that looks something like that shown in following function sample(). #include <new> using namespace std; class Fred { public: Fred() throw(); virtual ~Fred() throw(); }; void sample() throw(bad_alloc) { // Original code: Fred* p = new Fred(); Fred* p = (Fred*) operator new(sizeof(Fred)); <-- 1 try { new(p) Fred(); <-- 2 } catch (...) { operator delete(p); <-- 3 throw; <-- 4 } }
The statement new(p) Fred(); is called the placement new syntax (see FAQ 12.14). The effect is to call the Fred constructor, passing the pointer p as the constructor's this parameter. |