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<stringps(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