Heap allocated object's class constructor throws an exception.

M

Martin

Hi.

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?

Thanks in advance

Martin
 
M

mlimber

Martin said:
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-lite/dtors.html#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-lite/containers.html#faq-34.1.

Cheers! --M
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top