Item 37. AUTO_PTR
Difficulty: 8
This Item covers
basics about how you can use the standard auto_ptr safely
and effectively.
Historical note: The original simpler form of
this Item, appearing as a Special Edition of Guru of the Week, was first published in honor
of the voting out of the Final Draft
International Standard for Programming Language C++. It was
known/suspected that auto_ptr would change one last time
at the final meeting, where the standard was to be voted complete
(Morristown, New Jersey, November 1997), so this problem was posted
the day before the meeting began. The solution, freshly updated to
reflect the prior day's changes to the standard, became the first
published treatment of the standard auto_ptr.
Many thanks from all of us to Bill Gibbons, Greg
Colvin, Steve Rumsby, and others who worked hard on the final
refinement of auto_ptr. Greg, in particular, has labored
over auto_ptr and related smart pointer classes for many
years to satisfy various committee concerns and requirements, and
deserves public recognition for that work.
This problem, now with a considerably more
comprehensive and refined solution, illustrates the reasons for the
eleventh-hour changes that were made, and it shows how you can make
the best possible use of auto_ptr.
Comment on the following code: What's good,
what's safe, what's legal, and what's not?
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) ) );
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_;
};
|