Tuesday, May 20, 2008
What is auto_ptr?
  • auto_ptr is a smart pointer.
  • Owns a dynamically allocated object and performs cleanup when not needed.
  • Prevents memory leaks
  • The object destructor is called during destruction.
  • "release()" method could be used to take manual ownership of the object.
EXAMPLE: Demonstrate the auto_ptr releasing dynamically allocated object.

#include <iostream>

using namespace std;

class MyClass {
        int data1;
    public:
        MyClass() {
        data1 = 100;
    }
    void print() {
        cout << data1 << endl;
    }
};

void func() {

    auto_ptr<MyClass> ptr(new MyClass());

    ptr->print();

    // Delete not done
    // When ptr goes out of scope MyClass object is automatically destroyed
    // No memory leak is introduced
}

void main() {
    func();
}

OUTPUT:
100

4 comments :

  1. Why is this not a norm recommended by C++ .. even better, why does the internal C++ compiler not do this by default ?

    ReplyDelete
    Replies
    1. Very good question. Does anyone know the answer?

      Delete
  2. auto_ptr doesnt work for arrays.
    Also we cannot use auto_ptr twice in the same scope. it produces different results.
    So, we have shared_ptr to overcome disadvantages of auto_ptr

    ReplyDelete

Contact Form

Name

Email *

Message *

Back to Top