Tuesday, May 20, 2008

C++ Auto_Ptr

1 comment
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
If You Enjoyed This, Take 5 Seconds To Share It

1 comment:

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

    ReplyDelete