FAQ 12.17 In pnew Fred() , does the Fred memory leak if the Fred constructor throws an exception?

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

graphics/new_icon.gif

No, the system straightens things out automatically.

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.

  1. sizeof(Fred) bytes of memory are allocated using the memory allocation primitive void* operator new(size_t nbytes). This primitive is similar in spirit to malloc(size_t nbytes) (however operator new(size_t) and malloc(size_t) are not interchangeable; the two memory allocation primitives may not even use the same heap!). Recall that size_t is a typedef for some unsigned integral type such as unsigned int. Many system headers cause this typedef to be defined.

  2. A Fred object is constructed in the returned memory location by calling the Fred constructor. Thus the pointer returned from the first step is passed as the constructor's this parameter. The call to the constructor is conceptually wrapped in a try block so that the memory can be released if the constructor throws an exception.

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   } } 

(1) Step 1: Allocate memory

(2) Step 2: Construct the object (see FAQ 12.14)

(3) Deallocate the memory

(4) Rethrow the exception the constructor threw

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.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net