2016-11-30 68 views
0

的拷貝構造函數我要管理如下二維數組:
的unique_ptr與向量:錯誤:調用隱式刪除XXX

std::vector<std::unique_ptr<int []>> vec(5, nullptr); 
vec[0] = std::make_unique<int []>(3); 
vec[1] = std::make_unique<int []>(4); 
... 

不過,我得到一個錯誤:

error: call to implicitly-deleted copy constructor of 'std::__1::unique_ptr< int [], std::__1::default_delete< int []> >'

+0

是否有一個原因,你不是'std :: vector >'? – Galik

+0

@Galik號但我只需要一個固定大小的數組,所以我使用原始數組。 – Yves

回答

4

我認爲這個問題是您vector constructor call2 :填寫構造):

std::vector<std::unique_ptr<int []>> vec(5, nullptr); 

這裏,y你本質上是調用vector(size_t(5), std::unique_ptr<int[]>(nullptr))。請注意,這將創建一個std::unique_ptr的臨時實例,從您的nullptr參數隱式轉換/構建。然後vector構造函數應該複製你傳遞給它的值n來填充容器;因爲你不能複製任何unique_ptr(即使是空的),你會從該構造函數的代碼中得到編譯器錯誤。

如果你立即更換那些最初nullptr值,你應該建立一個空的vectorpush_back新的元素:

std::vector<std::unique_ptr<int []>> vec; // default constructor 
vec.push_back(std::make_unique<int []>(3)); // push the elements (only uses the move 
vec.push_back(std::make_unique<int []>(4)); // constructor of the temporary) 
... 

要使用一定數量空值的初始化vector,省略了第二個參數:

std::vector<std::unique_ptr<int []>> vec(5); 

這將構造每個unique_ptrdefault constructor,不需要任何複製。

-2

您正在插入整數元素,其中是期望的數組。

+2

你確定嗎?我不這麼認爲。 – Yves

+0

你定義了一個向量,該向量接收數組** int [] **的unique_ptr,並且當你使用vec [0]時,它需要一個int []變量。 –

+2

http://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique – Yves

2
std::vector<std::unique_ptr<int []>> vec(5, nullptr); 

此行拷貝構建從nullptr構造的臨時5 std::unique_ptr<int []>。這是非法的。

我想你想要這樣的:

std::vector<std::unique_ptr<int []>> vec; 
vec.reserve(5); 
vec.push_back(std::make_unique<int []>(std::size_t(3))); 

如果你真的想用5 nullptr一個向量,這裏是解決方案:

std::vector<std::unique_ptr<int []>> vec(5); 
vec[0] = std::make_unique<int []>(std::size_t(3));