Martin wrote:
Quote:
I've found a few topics on this subject, but still not sure and decided
to post mine.
>
Here's my example:
>
#include <iostream>
using namespace std;
>
class A
{
public:
A() { throw 0; }
};
>
int main()
{
try
{
A *pA = new A;
delete pA;
}
catch (...)
{
}
}
>
An object of class A is created in the heap, but the constructor throws
an exception. I know, that the destructor of the class won't be called,
and really I don't need that, because my class itself doesn't allocates
any resources. But what happens with memory allocated for the object
itself? After all, the first thing done by 'new' is allocating enough
memory for the object. So, who's responsible for deallocating it in
such a case?
|
The memory is automatically cleaned up. Buried in FAQ 11.14
(
http://www.parashift.com/c++-faq-lit...tml#faq-11.14), you'll
find this snippet of code which is what happens when using new:
// This is functionally what happens with Foo* p = new Foo()
Foo* p;
// don't catch exceptions thrown by the allocator itself
void* raw = operator new(sizeof(Foo));
// catch any exceptions thrown by the ctor
try {
p = new(raw) Foo(); // call the ctor with raw as this
}
catch (...) {
// oops, ctor threw an exception
operator delete(raw);
throw; // rethrow the ctor's exception
}
As for A allocating its own memory before its constructor throws,
that's why you should use RAII techniques (such as smart pointers and
vectors) to control such memory. See
http://www.parashift.com/c++-faq-lit....html#faq-34.1.
Cheers! --M