Is it possible to "delete" auto_ptr or scoped_ptr?

A

A

I know that I can delete this:

TStruct *a = new TStruct();
delete a;

but is it possible to delete this too:

std::auto_ptr<TStruct> a(new TStruct());

or this

boost::scoped_ptr<TStruct> a(new TStruct());

Basically, I'd like to use the advantages of auto_ptr or scoped_ptr but with
ability to remove them from memory when they are not needed but function
didn't terminate yet.

I see there is a reset() - is that what I need?

in other words, how do i call auto_ptr or scoped_ptr destructor?
 
A

A

I think a.reset() does what I want (releases pointer and frees memory for
both auto_ptr and boost::scoped_ptr) but I'd just like to confirm this here.
 
M

Marcel Müller

A said:
but is it possible to delete this too:

std::auto_ptr<TStruct> a(new TStruct());

or this

boost::scoped_ptr<TStruct> a(new TStruct());

Of course! Simply assign NULL to either of them. It will do what you want.

I see there is a reset() - is that what I need?

Yes. This is equivalent to assigning NULL.

in other words, how do i call auto_ptr or scoped_ptr destructor?

You should never ever call the destuctor directly. Setting them to NULL
is not the same since they might point to other objects later.


Marcel
 
J

jl_post

I know that I can delete this:

TStruct *a = new TStruct();
delete a;

but is it possible to delete this too:

std::auto_ptr<TStruct> a(new TStruct());

I see there is a reset() - is that what I need?


I don't know about scoped_ptr, but with std::auto_ptr you just need
to give it another pointer with ::reset(), and the memory it currently
points to will be deleted (freed).

NULL is a valid value to pass ::reset() (which is what it defaults
to anyway), so you can just use:

a.reset(); // frees/deleted what a was pointing to

Now the a variable will be pointing to NULL, so be careful about de-
referencing it, or else your program will likely crash.

I hope this helps.

-- Jean-Luc
 
A

A

I don't know about scoped_ptr, but with std::auto_ptr you just need
to give it another pointer with ::reset(), and the memory it currently
points to will be deleted (freed).

scoped_ptr is almost identical to auto_ptr except it is non-copyable by
default. it also has reset(), probably the NULL trick would do work as well.
 

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

Latest Threads

Top