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

标签 c++ c++11 destructor copy-constructor unique-ptr

编译以下代码:

#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 时自动生成的移动构造函数。添加用户声明的析构函数可防止编译器自动生成析构函数。例如,参见 thisthis问题。并且编译器生成的复制构造函数不能使用,因为成员 upstd::unique_ptrunique_ptr 的复制构造函数被显式删除。

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

class Ship
{
public:
    Ship(){}
    Ship(Ship&&) = default;
    ~Ship(){}
    std::unique_ptr<container> up;
};

关于c++ - 为什么插入用户定义的析构函数需要用户定义的复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42535584/

相关文章:

c++ - 依赖于构造函数的类模板参数

c++ - 使用 OpenCV 消除视频帧失真

c++ - Visual Studio 2013 C++ 不编译更改

c++ - 来自给定输入的理性算术

C++ Pimpl Idiom 使用预先存在的类

c++ - 在 C++ 中通过析构函数销毁动态数组的 vector

c++ - 调用函数并传递存储在元组中的参数?

c++ - 在 C++ 中,是否可以强制用户捕获异常?

c++ - Dev-C++ 和 Code::Blocks 中的析构函数困惑

c++ - 实现链表 : head insertion and destructor