2009年3月20日 星期五

What is auto pointer?

The simplest example of a smart pointer is auto_ptr, which is included in the standard C++ library. Auto Pointer only takes care of Memory leak and does nothing about dangling pointers issue. Auto_ptr is a simple wrapper around a regular pointer. It forwards all meaningful operations to this pointer (dereferencing and indirection). Its smartness in the destructor: the destructor takes care of deleting the pointer.

For the user of auto_ptr, this means that instead of writing:

void foo()
{
MyClass* p(new MyClass);
p->DoSomething();
delete p;
}

You can write:

void foo()
{
auto_ptr p(new MyClass);
p->DoSomething();
}
And trust p to cleanup after itself

If you use auto_ptr objects you would not have to be concerned with heap objects not being deleted even if the exception is thrown.

沒有留言:

張貼留言