#include #include using std::cout; using std::endl; struct holder { int val; }; void grab_autoptr(std::auto_ptr arg) { cout << "func arg = " << arg.get() << endl; if ( arg.get() ) cout << "arg->val = " << arg->val << endl << endl; } std::auto_ptr give_autoptr() { std::auto_ptr x(new holder); x->val = 4; return x; } int main(int argc, char** argv) { // do not need to delete the holder object that is allocated std::auto_ptr p1(new holder); std::auto_ptr p2; p1->val = 3; cout << "p1 = " << p1.get() << endl << "p2 = " << p2.get() << endl; if ( p1.get() ) cout << "p1->val = " << p1->val << endl; if ( p2.get() ) cout << "p2->val = " << p2->val << endl; cout << endl; // transfer ownership of the pointer p2 = p1; cout << "p1 = " << p1.get() << endl << "p2 = " << p2.get() << endl; if ( p1.get() ) cout << "p1->val = " << p1->val << endl; if ( p2.get() ) cout << "p2->val = " << p2->val << endl; cout << endl; // transfer ownership of the pointer std::auto_ptr p3(p2); cout << "p1 = " << p1.get() << endl << "p2 = " << p2.get() << endl << "p3 = " << p3.get() << endl; if ( p1.get() ) cout << "p1->val = " << p1->val << endl; if ( p2.get() ) cout << "p2->val = " << p2->val << endl; if ( p3.get() ) cout << "p3->val = " << p3->val << endl; cout << endl; // this function will take over ownership of pointer grab_autoptr(p3); cout << "p1 = " << p1.get() << endl << "p2 = " << p2.get() << endl << "p3 = " << p3.get() << endl; if ( p1.get() ) cout << "p1->val = " << p1->val << endl; if ( p2.get() ) cout << "p2->val = " << p2->val << endl; if ( p3.get() ) cout << "p3->val = " << p3->val << endl; cout << endl; // this function will give ownership of a new pointer p1 = give_autoptr(); cout << "p1 = " << p1.get() << endl << "p2 = " << p2.get() << endl << "p3 = " << p3.get() << endl; if ( p1.get() ) cout << "p1->val = " << p1->val << endl; if ( p2.get() ) cout << "p2->val = " << p2->val << endl; if ( p3.get() ) cout << "p3->val = " << p3->val << endl; cout << endl; return 0; }