In P = new Fred (), does the Fred memory "leak" if the Fred constructor throws an exception?

Source: Internet
Author: User

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:

    1. 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!).
    2. 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:

  1. // Original code: Fred* p = new Fred();
  2. Fred* p;
  3. void* tmp = operator new(sizeof(Fred));
  4. try {
  5. new(tmp) Fred(); // Placement new
  6. p = (Fred*)tmp; // The pointer is assigned only if the ctor succeeds
  7. }
  8. catch (...) {
  9. operator delete(tmp); // Deallocate the memory
  10. throw; // Re-throw the exception
  11. }

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?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.