suppose that,we have following code
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_;
i am interested: What's good, what's safe, what's legal, and what's not in this code? as i know about auto_ptr is that,for example following code
#include <iostream>
#include <memory>
using namespace std;
int main(int argc, char **argv)
{
int *i = new int;
auto_ptr<int> x(i);
auto_ptr<int> y;
y = x;
cout << x.get() << endl; // Print NULL
cout << y.get() << endl; // Print non-NULL address i
return 0;
}
This code will print a NULL address for the first auto_ptr object and some non-NULL address for the second, showing that the source object lost the reference during the assignment (=). The raw pointer i in the example should not be deleted, as it will be deleted by the auto_ptr that owns the reference. In fact, new int could be passed directly into x, eliminating the need for i. how can i dtermine which line in my code is safe,which is not?
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) ));
The standard completely forbids this.