Auto_ptr problems

suppose we have the 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'm wondering: what's good, what's safe, what's legal, and what's not in this code? as i know about auto_ptr it is for example the 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, indicating that the original object lost its reference during assignment (=). The raw pointer i in this example should not be deleted as it will be deleted using the auto_ptr that this link belongs to. In fact, the new int can be cast directly to x, eliminating the need for i. how can I skip which line in my code is safe and which is not?


source to share

1 answer

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 prohibits this entirely.



All Articles