Auto_Ptr

来源:互联网 发布:stm32是单片机还是arm 编辑:程序博客网 时间:2024/04/30 12:04
auto_ptr<T> source() {return auto_ptr<T>( new T(1) );}void sink( auto_ptr<T> pt ) { }void f(){auto_ptr<T> a( source() );sink( source() );sink( auto_ptr<T>( new T(1) ) );// It is never safe to put auto_ptrs into standard containers.// For auto_ptr, copies are NOT equivalent.vector< auto_ptr<T> > v;v.push_back( auto_ptr<T>( new T(3) ) );v.push_back( auto_ptr<T>( new T(4) ) );v.push_back( auto_ptr<T>( new T(1) ) );v.push_back( a );v.push_back( auto_ptr<T>( new T(2) ) );sort( v.begin(), v.end() );cout << a->Value();}class C{public:    /*...*/protected: /*...*/private:   /*...*/auto_ptr<CImpl> pimpl_;};void f(){T* pt(new T);// auto_ptr<T> pt(new T);ok!/*...more code...*/delete pt;// if never execute at here? it will make memory leak.}void g(){T* pt1 = new T;auto_ptr<T> pt2(pt1);*pt2 = 12; // same as *pt1 =12;pt2->SomeFun(); // same as *pt1->SomeFunc();assert(pt2 == pt2.get());T* pt3 = pt2.release(); // take back owership.// calling reset() is much the same as destroying the auto_ptr and creating a new one that owns the new object.delete pt3;}void h(){auto_ptr<T> pt(new T(1));pt.reset(new T(2));}// Example 4(a): A typical Pimpl // file c.hclass C{public:C();~C();/*...*/private:struct CImpl; // forward declarationCImpl* pimpl_;// auto_ptr<CImpl> pimpl_;// new add:   // C& operator= (const C&);  // C(const C&);};// file c.cppstruct C::CImpl { /*...*/ };C::C() : pimpl_( new CImpl ) { }C::~C() { delete pimpl_; } // NEW: C:~C();// Example 5: Transferring ownership from  one auto_ptr to anothervoid f(){auto_ptr<T> pt1( new T );auto_ptr<T> pt2;pt1->DoSomething(); // OKpt2 = pt1;  // now pt2 owns the pointer,// and pt1 does notpt2->DoSomething(); // OK} // as we go out of scope, pt2's destructor deletes the pointer, but pt1's does nothing// Example 6: Never try to do work through a non-owning auto_ptrvoid f(){auto_ptr<T> pt1( new T );auto_ptr<T> pt2;pt2 = pt1;  // now pt2 owns the pointer, and pt1 does notpt1->DoSomething();// error: following a null pointer}void f( String& result ){cout << "some output";result = "some value";}// Correct (finally!) auto_ptr<String> f(){auto_ptr<String> result = new String;*result = "some value";cout << "some output";return result;// rely on transfer of ownership; this can't throw}const auto_ptr<T> pt1( new T ); // making pt1 const guarantees that pt1 can// never be copied to another auto_ptr, and// so is guaranteed to never lose ownershipauto_ptr<T> pt2( pt1 ); // illegalauto_ptr<T> pt3;pt3 = pt1;              // illegalpt1.release();          // illegalpt1.reset( new T );     // illegal