2016-04-14 23 views
0

這個簡單的代碼可以編譯。我不能使unique_ptr的列表<int>數組

unique_ptr<list<int>> map1(new list<int>[10]); 

但它在運行時會導致seg falutut。

的malloc:*錯誤對象0x7fe02a4032e8:被釋放的指針沒有被分配 *設置斷點malloc_error_break調試

但是這個代碼成功運行。

unique_ptr<int> map2(new int[10]); 

爲什麼使用unique_ptr無法創建列表數組?

在此先感謝。

+2

兩件的類型構造函數使用new[]代碼具有未定義的行爲並被破壞。 –

+0

參考[this](http://stackoverflow.com/questions/16711697/is-there-any-use-for-unique-ptr-with-array) – Incomputable

+2

一個'list '和一個'list [10 ]'是兩種不同的類型 – NathanOliver

回答

4

您需要使用的unique_ptr版動態分配數組:

std::unique_ptr<std::list<int>[]> map1(new std::list<int>[10]); 
           ^^ ~~~~~ ! 

在這裏看到:http://en.cppreference.com/w/cpp/memory/unique_ptr

template < 
    class T, 
    class Deleter 
> class unique_ptr<T[], Deleter>; 

您還可以使用std::make_unique(如在評論建議),您將獲得編譯錯誤而不是UB,因爲它的接口可以防止它:

std::unique_ptr<std::list<int>[]> up1 = std::make_unique<std::list<int>[]>(10); 
auto up2 = std::make_unique<std::list<int>[]>(10); 

但是,此代碼已成功運行。

unique_ptr map2(new int [10]);

它仍然未定義在上面的代碼中的行爲,它可能工作或可能會導致段錯誤。如上所述的unique_ptr接受任何指針,但在破壞期間將始終調用delete。在指向動態分配數組的指針上調用delete是UB。這就是爲什麼你需要撥打delete[]這是什麼unique_ptr動態分配陣列。

+2

這就是爲什麼人們應該使用'std :: make_unique',使得不可能使類型錯誤。 – GManNickG

+0

好點,我已經在回答中包含了這個 – marcinj

0

你需要的是:

std::unique_ptr<std::list<int>[]> map1(new std::list<int>[10]); 

Live Demo

1

一個A list<int>list<int>[10]兩種不同的類型。當你有一個

unique_ptr<list<int>> 

你告訴unique_ptr,它會指向一個list<int>。當unique_ptr超出範圍時,它將調用delete刪除基礎指針。偏偏你

new list<int>[10] 

這需要與delete []delete被刪除初始化。這是

unique_ptr<int> map2(new int[10]); 

相同爲什麼第一個版本失敗,第二個不?:Undefined behavior

這是不確定的行爲叫delete的東西,一直new[]

所以,如果你要在你需要使用type[]爲的unique_ptr

相關問題