No.
If An exception occurs during Fred
p = new Fred()
the constructor of, the C + + language guarantees that the memory sizeof(Fred)
bytes that Were allocated'll automagically is released back to the heap.
Here's the details: is new Fred()
a two-step process:
sizeof(Fred)
bytes of memory is allocated using the primitive void* operator new(size_t nbytes)
. This primitive was similar in spirit to malloc(size_t nbytes)
. (Note, however, that these, and not interchangeable; e.g., there was no guarantee that the memory Allocatio N Primitives even use the same heap!).
- It constructs an object in that memory by calling the
Fred
constructor. The pointer returned from the first step was passed as the this
parameter to the constructor. This step was wrapped in a ... block to handle, the case, an try
catch
exception was thrown during this step.
Thus The actual generated code is functionally similar to:
// Original code: Fred* p = new Fred();
Fred* p;
void* tmp = operator new(sizeof(Fred));
try {
new(tmp) Fred(); // Placement new
p = (Fred*)tmp; // The pointer is assigned only if the ctor succeeds
}
catch (...) {
operator delete(tmp); // Deallocate the memory
throw; // Re-throw the exception
}
The statement marked "Placement new
" calls the Fred
constructor. The pointer p
becomes this
the pointer inside the constructor, Fred::Fred()
.
In P = new Fred (), does the Fred memory "leak" if the Fred constructor throws an exception?