question about auto_ptr

B

Bruintje Beer

Does the code below solve memory leaks on variable m if there is an
exception thrown or do I have to cleanup the auto_ptr myself ?

void A::f()
{
try
{
auto_ptr<Object> m(new Object());

some exception thrown

}
catch(MyException& ex)
{
// some stuff
}
}
 
I

Ian Collins

Bruintje said:
Does the code below solve memory leaks on variable m if there is an
exception thrown or do I have to cleanup the auto_ptr myself ?
No, that's the function of std::auto_ptr.
void A::f()
{
try
{
auto_ptr<Object> m(new Object());

some exception thrown

the object will be freed here.
 
V

Vincent Jacques

Bruintje Beer a écrit :
Does the code below solve memory leaks on variable m if there is an
exception thrown or do I have to cleanup the auto_ptr myself ?

As soon as you put your pointer in auto_ptr, you're assured it will be
deleted when the auto_ptr is destroyed.
void A::f()
{
try
{
auto_ptr<Object> m(new Object());

some exception thrown

}
catch(MyException& ex)
{
// some stuff
}
}

In this code, the auto_ptr is destroyed at the end of the try block
(exception thrown or not), so there is no memory leak.

Cheers,
 

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

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,610
Members
45,255
Latest member
TopCryptoTwitterChannels

Latest Threads

Top