Several new's in an expression with constructors throwing exceptio
If we have an expression like
A* p = new A;
and A's constructor throws an exception, memory allocated by 'new' will be
de-allocated (by an appropriate 'delete'). How will this work if we have an
expression with several new's?
I have been trying this:
-------------------------------------------------------------
struct A {
A() { throw "Help A!"; }
//A() { std::cout << "A created.\n"; }
~A() { std::cout << "A destroyed.\n"; }
};
struct B {
//B() { throw "Help B!"; }
B() { std::cout << "B created.\n"; }
~B() { std::cout << "B destroyed.\n"; }
};
void fAAB(A* pa1, A* pa2, B* pb)
{
std::cout << "fAAB: pa1 = " << pa1 << ", pa2 = " << pa2 << ", pb = " << pb
<< std::endl;
}
int _tmain(int /*argc*/, _TCHAR* /*argv[]*/)
{
A *pa1 = 0, *pa2 = 0;
B* pb = 0;
try {
std::cout << "unallocated: pa1 = " << pa1 << ", pa2 = " << pa2 << ", pb =
" << pb << std::endl;
fAAB(pa1 = new A, pa2 = new A, pb = new B);
std::cout << "allocated: pa1 = " << pa1 << ", pa2 = " << pa2 << ", pb = "
<< pb << std::endl;
delete pa1;
delete pa2;
delete pb;
}
catch (const char* s) {
std::cerr << "Exception: " << s << ", pa1 = " << pa1 << ", pa2 = " << pa2
<< ", pb = " << pb << std::endl;
}
catch (...) {
std::cerr << "Exception: pa1 = " << pa1 << ", pa2 = " << pa2 << ", pb = "
<< pb << std::endl;
}
}
-------------------------------------------------------------
and the result was that when A threw an exception and B did not (the third
argument - 'new B' - happened to be created first), all pa1, pa2 and pb
remained NULLs and B had its constructor invoked.
I understand that it will not be the implementation's job to call B's
destructor in this scenario (B did not throw an exception, and so no need to
call 'delete') but then pb was not assigned to, either. Does this mean there
is no way to de-allocate pb in this case (obviously there is no code to do
this in the above example but pb remains NULL anyway).
Thank you.
Paul