Using auto_ptr. - C++ Data Type

C++ examples for Data Type:auto_ptr

Description

Using auto_ptr.

Demo Code

#include <iostream>
#include <memory>
using namespace std;
class X {// w ww .ja  v a 2s .c  o m
   public:
   int v;
   X(int j) {
      v = j;
      cout << "Constructing X(" << v <<")\n";
   }
   ~X() { cout << "Destructing X(" << v <<")\n"; }
   void f() { cout << "Inside f()\n"; }
};
int main()
{
   auto_ptr<X> p1(new X(3)), p2;
   cout << "p1 points to an X with the value " << p1->v
   << "\n\n";
   // Transfer ownership to p2.
   cout << "Assigning p1 to p2.\n";
   p2 = p1;
   cout << "Now, p2 points to an X with the value " << p2->v
   << endl;
   if(!p1.get()) cout << "p1's pointer is now null.\n\n";

   cout << "Call f() through p2: ";
   p2->f();
   cout << endl;

   cout << "Get the pointer stored in p2 and assign it to a\n"
   << "normal pointer called ptr.\n";
   X *ptr = p2.get();
   cout << "ptr points to an X with the value " << ptr->v
   << "\n\n";
   return 0;
}

Result


Related Tutorials