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.
others_.push_back( testptr( new test(other) ) );
You are trying to push an auto_ptr
into a std::vector
auto_ptr
does not define an implicit copy constructor and is not compatible as a value in the stl container classes.
See this question for more info: StackOverflow: Why is it wrong to use stdauto ptr with stl containers
You cannot create standard library containers of auto_ptr, as you are trying to do here:
std::vector< testptr > others_;
as they do not have the correct semantics. You will have to use ordinary pointers or a different flavour of smart pointer, such as shared_ptr
.
You probably want std::unique_ptr or std::shared_ptr from the upcoming C++0x standard which will replace auto_ptr if you have access to a compiler that has these implemented (gcc 4.5+)
http://www2.research.att.com/~bs/C++0xFAQ.html#std-unique_ptr http://www2.research.att.com/~bs/C++0xFAQ.html#std-shared_ptr
精彩评论