No.
If an exception occurs during the Fred
constructor of p = new Fred()
, the C++ language guarantees that the memory sizeof(Fred)
bytes that were allocated will automagically be released back to the heap.
Here are the details: new Fred()
is a two-step process:
sizeof(Fred)
bytes of memory are allocated using the primitivevoid* operator new(size_t nbytes)
. This primitive is similar in spirit tomalloc(size_t nbytes)
. (Note, however, that these two are not interchangeable; e.g., there is no guarantee that the two memory allocation 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 is passed as thethis
parameter to the constructor. This step is wrapped in atry
…catch
block to handle the case when an exception is 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 the this
pointer inside the constructor, Fred::Fred()
.
时间: 2024-10-06 23:03:09