#include #include using namespace std; class Object { public: Object( ) { id = count++; } virtual ~Object( ) { cout << "Calling destructor for object " << id << endl; } int getID( ) const { return id; } private: int id; static int count; }; int Object::count = 0; // In pattern #1, object needs to be created // and deleted in same scope. // Note that -> is overloaded for auto_ptr. void pattern1( ) { cout << "Starting pattern1" << endl; Object *o1 = new Object( ); auto_ptr p1( o1 ); cout << "The object's id is " << p1->getID( ) << endl; cout << "Exiting from pattern1" << endl; } // Note that auto_ptr is returned using // call by value, which transfers control. auto_ptr getPtr( ) { Object *o2 = new Object( ); return auto_ptr( o2 ); } // In pattern #2, object is created in one // scope and returned back to second scope, // where it needs to be deleted. void pattern2( ) { cout << "Starting pattern2" << endl; auto_ptr p2 = getPtr( ); cout << "The object's id is " << p2->getID( ) << endl; cout << "Exiting from pattern2" << endl; } // Note that auto_ptr is passed using call // by value, which transfers control. void usePtr( auto_ptr p3 ) { cout << "Entering usePtr" << endl; cout << "The object's id is " << p3->getID( ) << endl; cout << "Exiting usePtr" << endl; } // In pattern #3, object needs to be created // in one scope, sent to another scope, and // deleted there. void pattern3( ) { cout << "Starting pattern3" << endl; Object *o3 = new Object( ); usePtr( auto_ptr( o3 ) ); cout << "Exiting from pattern3" << endl; } int main( ) { pattern1( ); pattern2( ); pattern3( ); return 0; }