top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is auto pointer in C++?

+2 votes
275 views
What is auto pointer in C++?
posted Dec 29, 2014 by Emran

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

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. You can find it in the header . Here is part of auto_ptr's implementation, to illustrate what it does:

 template class auto_ptr
 {
  T* ptr;

  public: 
  explicit auto_ptr(T* p = 0) : ptr(p) {}

  ~auto_ptr() {delete ptr;}

  T& operator*()
  {return *ptr;}

  T* operator->()
  {return ptr;} 
  // ...
 };    

As you can see, 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.

answer Dec 30, 2014 by Mohammed Hussain
...