【发布时间】:2010-08-06 00:04:39
【问题描述】:
有人能解释一下为什么我在这里遇到编译错误 - 错误 C2558: class '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;
}
【问题讨论】:
-
好久没做C++了,不应该是
g = test<std::string>("d");吗? -
@Jesse J:两者都可以。这两种方式的行为略有不同,除了最邪恶的情况外,所有情况下都给出相同的结果。从技术上讲,您的方法将创建一个测试类,然后将其分配给 g,而不仅仅是初始化 g 本身。只有当您有自定义复制/分配/初始化行为时,这才会成为问题。
-
谢谢大家。真正翔实的答案。
标签: c++ compiler-errors cautoptr