下面的代碼編譯:爲什麼用戶定義的析構函數的插入需要一個用戶定義的複製構造
#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甚至不能被複制。
https://godbolt.org/g/rFoUWi - 鐺3.9.1在這裏所做的行爲這樣 – Ap31
還鏗鏘: 錯誤(S): source_file.cpp:27:12:錯誤:調用隱含缺失 '船舶' 的拷貝構造函數 返回TMP; ... – newandlost
是,所有4個編譯器說副本定義析構函數時,構造函數會被隱式刪除 – Ap31