c – 为什么插入用户定义的析构函数需要用户定义的复制构造函数
发布时间:2020-12-16 10:13:49 所属栏目:百科 来源:网络整理
导读:以下代码编译: #include vector#include iostream#include memoryusing namespace std;class container{public: container(){} ~container(){}};class Ship{public: Ship(){} //Ship(const Ship other){cout"COPY"endl;} //~Ship(){} std::unique_ptrcontai
以下代码编译:
#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; }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |