Fortunately
After running a1 and a destructor will be called. This confused me. Since b
is created in heap, and a and a1 is also on heap, how come exception can
call a1 and a's destructor.
First, there is the concept of a "fully constructed object". An object is
fully constructed when its constructor body has been run. When an exception
happens during object creation, all the things that are fully constructed get
their destructors run.
In this case what happens when you call new B:
1. sizeof(B) bytes is allocated by the global operator new.
2. B's subobjects are constructed. B::a is constructed by dynamically
creating an A object (I'll omit the details of this) dynamically and feeding
it to the auto_ptr constructor. B::a is now fully constructed at this point.
3. B::a1 is default constructed. B::a1 is now fully constructed.
4. The constructor body of B is run.
5. The throw expression is encountered.
6. The compiler now destructs all of the fully constructed parts of B in reverse order:
B::a1 is destroyed.
7. B::a is destroyed, the auto_ptr destructor deletes the referenced A object.
8. The global operator delete is called to return the memory used by B.
9. The stack is unwound up to the point where the handler is found... and control
is transferred there.