delete resouce of partial constructed object

M

Metaosp

Hi, I have a question regarding the partially constructed object. If an
exception occurs while executing object's constructor, how can I delete
the resource that might have been allocated? For example:

class Foo {};

class Bar {
public:
Bar() {
f = new Foo();
throw Exception();
}
private:
Foo *f;
};

int main() {
try {
Bar *b = new Bar();
} catch (exception e) {

// What happened to *f ? How can I delete it?
}
}


Thanks,
Metaosp
 
R

Rolf Magnus

Metaosp said:
Hi, I have a question regarding the partially constructed object. If an
exception occurs while executing object's constructor, how can I delete
the resource that might have been allocated?

se the RAII principle.
For example:

class Foo {};

class Bar {
public:
Bar() {
f = new Foo();
throw Exception();
}
private:
Foo *f;
};

int main() {
try {
Bar *b = new Bar();
} catch (exception e) {

// What happened to *f ? How can I delete it?

You can't.

One way of solving it is by using std::auto_ptr, like:

Bar() {
std::auto_ptr<Foo> ptr(new Foo);
throw Exception();
f = ptr->release();
}

Do you actually need to allocate the member dynamically?
 
M

mlimber

Rolf said:
se the RAII principle.


You can't.


One way of solving it is by using std::auto_ptr, like:

Bar() {
std::auto_ptr<Foo> ptr(new Foo);
throw Exception();
f = ptr->release();
}

Or better, just make Bar::f (don't try to pronounce it) a smart pointer
instead of a raw pointer. Also prefer initialization lists
(http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6), and prefer
to catch your exception by reference rather than value
(http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.7):

class Bar
{
public:
Bar()
: f( new Foo )
{
throw Exception();
}
private:
std::auto_ptr<Foo> f;
};

int main()
{
try
{
Bar *b = new Bar();
}
catch( const Exception& e )
{
// ...
}
return 0;
}

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,755
Messages
2,569,537
Members
45,021
Latest member
AkilahJaim

Latest Threads

Top