Could somebody please explain why I’m getting a compile error here – error C2558: class ‘std::auto_ptr<_Ty>’ : no copy constructor available or copy constructor is declared ‘explicit’
#include <memory>
#include <vector>
#include <string>
template<typename T>
struct test
{
typedef std::auto_ptr<T> dataptr;
typedef std::auto_ptr< test<T> > testptr;
test( const T& data ):
data_( new T(data) )
{
};
void add_other( const T& other )
{
others_.push_back( testptr( new test(other) ) );
}
private:
dataptr data_;
std::vector< testptr > others_;
};
int main(int argc, char* argv[])
{
test<std::string> g("d");
//this is the line that causes the error.
g.add_other("d");
return 0;
}
Basically a
std::auto_ptrcannot be used in this way.Requires that a copy constructor that takes a
const&exists and no such constructor exists forstd::auto_ptr. This is widely viewed as a good thing since you should never usestd::auto_ptrin a container! If you do not understand why this is, then read this article by Herb Sutter, particularly the section entitled “Things Not To Do, and Why Not To Do Them” about 3/4 of the way through.