我有以下代码
class A {
public:
A(){}
~A(){}
private:
std::vector<std::unique_ptr<double> > x;
};
A f() {
A a;
return a;
}
int main() {
A a=f();
return 0;
}
除非我注释掉析构函数,否则它不会编译(gcc 4.7)。实际上,我的代码中并不需要这个析构函数,我只是想将它用于调试目的。
但是,我不明白发生了什么,因此我担心我做错了什么。这里发生了什么?
最佳答案
这是因为显式定义的析构函数的存在阻止了为 A
隐式生成移动构造函数。
根据 C++11 标准的第 12.8/9 段:
If the definition of a class X does not explicitly declare a move constructor, one will be implicitly declared as defaulted if and only if
— X does not have a user-declared copy constructor,
— X does not have a user-declared copy assignment operator,
— X does not have a user-declared move assignment operator,
— X does not have a user-declared destructor, and
— the move constructor would not be implicitly defined as deleted.
现在没有移动构造函数,为了从 f()
返回值,编译器将尝试调用隐式生成的复制构造函数(为了向后兼容仍在生成该构造函数)。但是,std::unique_ptr
是不可复制的。因此,错误。
显式定义移动构造函数(或将其声明为默认构造函数,如评论中 juanchopanza 的建议)将解决问题。
关于c++ - 析构函数和 unique_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15485863/