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.h
class C
{
public:
C();
~C();
/*...*/
private:
struct CImpl; // forward declaration
CImpl* pimpl_;// auto_ptr<CImpl> pimpl_;
// new add: // C& operator= (const C&);
// C(const C&);
};
// file c.cpp
struct C::CImpl { /*...*/ };
C::C() : pimpl_( new CImpl ) { }
C::~C() { delete pimpl_; } // NEW: C:~C();
// Example 5: Transferring ownership from one auto_ptr to another
void f()
{
auto_ptr<T> pt1( new T );
auto_ptr<T> pt2;
pt1->DoSomething(); // OK
pt2 = pt1; // now pt2 owns the pointer,
// and pt1 does not
pt2->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_ptr
void f()
{
auto_ptr<T> pt1( new T );
auto_ptr<T> pt2;
pt2 = pt1; // now pt2 owns the pointer, and pt1 does not
pt1->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 ownership
auto_ptr<T> pt2( pt1 ); // illegal
auto_ptr<T> pt3;
pt3 = pt1; // illegal
pt1.release(); // illegal
pt1.reset( new T ); // illegal
Auto_Ptr
最新推荐文章于 2024-03-25 01:36:05 发布