Car*_*arl 5 c++ compiler-errors cautoptr
有人可以解释为什么我在这里收到编译错误 - 错误C2558:类'std :: auto_ptr <_Ty>':没有可用的复制构造函数或者复制构造函数被声明为'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;
}
Run Code Online (Sandbox Code Playgroud)
others_.push_back( testptr( new test(other) ) );
Run Code Online (Sandbox Code Playgroud)
你正试图推进auto_ptr一个std::vector
auto_ptr 没有定义隐式复制构造函数,并且不兼容stl容器类中的值.
有关更多信息,请参阅此问题:StackOverflow:为什么将stdauto ptr与stl容器一起使用是错误的
基本上std::auto_ptr不能以这种方式使用.
others_.push_back( testptr( new test(other) ) );
Run Code Online (Sandbox Code Playgroud)
需要存在一个复制构造函数,const&该构造函数存在一个存在且不存在这样的构造函数std::auto_ptr.这被广泛认为是好事,因为你永远不应该std::auto_ptr在容器中使用! 如果您不明白为什么会这样,那么请阅读Herb Sutter撰写的这篇文章,特别是关于3/4通过的题为"不做的事情,为什么不做"的部分.
| 归档时间: |
|
| 查看次数: |
13124 次 |
| 最近记录: |