Magic about auto_ptr !!

B

Binary

Hi,

I am reading a chinese book about STL, the book says below code will
have no memory leak. I think its magic and wonder why the auto_ptr
knows the memory should be freed when leaving the function call:

void func()
{
auto_ptr<string> ps(new string("jjhou"));
cout << *ps << endl;
// leave the function without delte, the auto_ptr will release it
automatically
}

TIA.
ABAI
 
B

benben

I am reading a chinese book about STL, the book says below code will
have no memory leak. I think its magic and wonder why the auto_ptr
knows the memory should be freed when leaving the function call:

void func()
{
auto_ptr<string> ps(new string("jjhou"));
cout << *ps << endl;
// leave the function without delte, the auto_ptr will release it
automatically
}

A google on auto_ptr should give you tons of information. Basically, the
auto_ptr class template is an example of how RAII idiom can help
resource management.

But before you get too excited please note that auto_ptr may not the be
all and end all solution--far from it, in fact. Google on it, see what
restrictions it has and what policy it imposes.

That said, auto_ptr is a handy tool to use in the face of exception
safety simply by the fact that it is properly destroyed (unlike a raw
pointer) during stack unwinding. Again, google on it.

Regards,
Ben
 
Y

Ye Dafeng

Binary said:
Hi,

I am reading a chinese book about STL, the book says below code will
have no memory leak. I think its magic and wonder why the auto_ptr
knows the memory should be freed when leaving the function call:

void func()
{
auto_ptr<string> ps(new string("jjhou"));
cout << *ps << endl;
// leave the function without delte, the auto_ptr will release it
automatically
}

TIA.
ABAI

I suggest you read << C++ Primer >>, maybe you can find what you want.
 
C

Clark S. Cox III

Binary said:
Hi,

I am reading a chinese book about STL, the book says below code will
have no memory leak. I think its magic and wonder why the auto_ptr
knows the memory should be freed when leaving the function call:

Because that is what auto_ptr's destructor does; it deletes the pointer
that it is holding on to.
 

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,744
Messages
2,569,484
Members
44,905
Latest member
Kristy_Poole

Latest Threads

Top