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_ptr
cannot be used in this way.
others_.push_back( testptr( new test(other) ) );
Requires that a copy constructor that takes a const&
exists and no such constructor exists for std::auto_ptr
. This is widely viewed as a good thing since you should never use std::auto_ptr
in 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With