编译以下代码:
#include <vector>
#include <iostream>
#include <memory>
using namespace std;
class container
{
public:
container(){}
~container(){}
};
class Ship
{
public:
Ship(){}
//Ship(const Ship & other){cout<<"COPY"<<endl;}
//~Ship(){}
std::unique_ptr<container> up;
};
Ship buildShip()
{
Ship tmp;
return tmp;
}
int main(int argc, char *argv[])
{
return 0;
}
但是如果我们包含用户定义的析构函数 ~Ship(){}
,如果我们还包括用户定义的复制构造函数,代码将仅编译 Ship(const Ship & other){cout<<"COPY"<<endl;}
简而言之:
编译:
Ship(){}
//Ship(const Ship & other){cout<<"COPY"<<endl;}
//~Ship(){}
编译:
Ship(){}
Ship(const Ship & other){cout<<"COPY"<<endl;}
~Ship(){}
不编译:
Ship(){}
//Ship(const Ship & other){cout<<"COPY"<<endl;}
~Ship(){}
为什么插入用户定义的析构函数需要一个用户定义的复制构造函数,为什么我们在上面的例子中根本需要一个复制构造函数?
我希望上面的示例中不需要复制构造函数,因为 unique_ptr 甚至无法复制。
最佳答案
代码被编译是因为 buildShip()
将使用编译器在返回 tmp
时自动生成的移动构造函数。添加用户声明的析构函数可防止编译器自动生成析构函数。例如,参见 this或 this问题。并且编译器生成的复制构造函数不能使用,因为成员 up
是 std::unique_ptr
。 unique_ptr
的复制构造函数被显式删除。
所以这将编译,因为明确要求编译器生成移动构造函数:
class Ship
{
public:
Ship(){}
Ship(Ship&&) = default;
~Ship(){}
std::unique_ptr<container> up;
};
关于c++ - 为什么插入用户定义的析构函数需要用户定义的复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42535584/