// ========================================================================== // $Id: uniqueptr.cpp,v 1.1 2013/11/24 22:50:25 jlang Exp $ // CSI2372 example Code for lecture 13 // ========================================================================== // (C)opyright: // // Jochen Lang // EECS, University of Ottawa // 800 King Edward Ave. // Ottawa, On., K1N 6N5 // Canada. // http://www.site.uottawa.ca // // Creator: jlang (Jochen Lang) // Email: jlang@site.uottawa.ca // ========================================================================== // $Log: uniqueptr.cpp,v $ // Revision 1.1 2013/11/24 22:50:25 jlang // Added examples on weak and unique ptr. // // ========================================================================== #include #include using std::endl; using std::cout; using std::auto_ptr; using std::ostream; class A { int d_a; public: A( int _a = 0) : d_a(_a) { cout << "A(" << _a << ")" << endl; } A operator++ (int) { A res(*this); ++(*this); return res; } A& operator++ () { ++d_a; return *this; } int getValue() { return d_a; } friend ostream& operator<<(ostream& os, const A& _obj ) { os << "A: " << _obj.d_a; return os; } }; int main() { std::unique_ptr aPtr(new A(3)); // calling a function on A cout << "Value: " << aPtr->getValue() << endl; // derefencing to get A ++(*aPtr); cout << *aPtr << endl; std::unique_ptr aPtr2; // aPtr2 is a nullptr // Now transfer ownership aPtr2.reset(aPtr.release()); cout << "aPtr: " << aPtr.get() << endl; cout << *aPtr2 << endl; aPtr2.release(); cout << "aPtr2: " << aPtr2.get() << endl; return 0; }