/////////////////////////////////////////////////////////////////////// // auto_ptr.cpp - demonstrate use of auto_ptr class from // // // // Jim Fawcett, CSE687 - Object Oriented Design, Spring 2001 // /////////////////////////////////////////////////////////////////////// /* The auto_ptr class manages ownership of a single object allocated on the heap. When an auto_ptr is constructed, it takes ownership of pointer passed in its constructor argument. That implies that: - auto_ptr assignment transfers ownership to the assignee. - auto_ptr will destruct an object it owns when it goes out of scope. That includes when an exception is thrown. ---NOTE--- Copy construction and assignment cause the source to change, e.g., the source auto_ptr loses ownership. This is not allowed for STL containers, so you can't use them there. You can't use auto_ptrs for arrays. The auto_ptr destructor calls delete, not delete [], so array ownership does not work. Fortunately it fails at compile time, in case you forget. */ #pragma warning(disable : 4786) #include #include // here is where auto_ptr is declared using namespace std; //----< an object defined only for this demonstration >------------ class test { public: test() { cout << "\n constructing a test object"; } ~test() { cout << "\n destroying a test object"; } void accept(const string &s) { testStr = s; } void say() { cout << "\n " << testStr.c_str(); } private: string testStr; }; //----< function to test auto_ptr when an exception is thrown >---- template void testAutoPtr(auto_ptr apT) /*thow(exception)*/ { apT->say(); cout << "\n Now we are going to throw an exception"; throw exception("exception thrown in testAutoPtr(...)"); } // //----< test stub >------------------------------------------------ void main() { cout << "\n Demonstrate use of auto_ptr objects " << "\n =====================================\n"; auto_ptr pTest(new test); try { pTest->accept("this is a test object speaking"); testAutoPtr(pTest); } ////////////////////////////////////////////////////////////////// // auto_ptr.get() is supposed to return NULL when it does not // // have ownership. As you will see by looking at the display // // of this handler, Visual C++ auto_ptr does not conform. // ////////////////////////////////////////////////////////////////// catch(exception &e) { cout << "\n\n Entering Exception Handler\n " << e.what() << "\n"; if(pTest.get() == NULL) cout << " auto_ptr is compliant with the C++ standard\n"; else cout << " auto_ptr is not compliant with the C++ standard\n"; } cout << "\n\n"; }