为什么插入用户定义的析构函数需要用户定义的复制构造函数

2023-12-11

以下代码编译:

#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 or this问题。并且编译器生成的复制构造函数不能使用,因为该成员up这是std::unique_ptr。和复制构造函数unique_ptr被明确删除。

所以这将编译,因为编译器被明确要求生成移动构造函数:

class Ship
{
public:
    Ship(){}
    Ship(Ship&&) = default;
    ~Ship(){}
    std::unique_ptr<container> up;
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么插入用户定义的析构函数需要用户定义的复制构造函数 的相关文章

随机推荐