Connecting Tech Pros Worldwide Help | Site Map

Heap allocated object's class constructor throws an exception.

  #1  
Old November 15th, 2006, 11:35 AM
Martin
Guest
 
Posts: n/a
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

  #2  
Old November 15th, 2006, 11:45 AM
mlimber
Guest
 
Posts: n/a

re: Heap allocated object's class constructor throws an exception.


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

Closed Thread


Similar Threads
Thread Thread Starter Forum Replies Last Post
.Net frameword Resources ( vb.net , asp.net etc...) shamirza answers 0 January 17th, 2007 08:05 AM
heap vs. stack Brian Buderman answers 9 December 18th, 2006 05:55 PM
heap allocating classes Shailesh Humbad answers 4 July 22nd, 2005 11:36 AM
opeator new question: again! john sun answers 2 July 22nd, 2005 06:15 AM