2013-02-17 21 views
1

我知道這種問題在這裏不是很受歡迎,但我必須問: 爲什麼unique_ptr/shared_ptr/etc爲T類型有一個operator = overload?缺少unique_ptr和朋友operator = overload

這似乎更自然寫的

std::unique_ptr<int> p = new int(5); 

代替

std::unique_ptr<int> p(new int(5)); 

或任何其他更詳細的方法。

+0

其實我錯了,你的第一個表單也沒有編譯;-)對不起! (這是調用構造函數,但它看起來像不能創建一個臨時傳遞給複製ctor。) – Cameron 2013-02-17 01:02:33

+0

我知道它不會編譯,這就是要點 – user1233963 2013-02-17 01:03:37

+0

看起來像[這個問題]的副本(http (http://stackoverflow.com/q/757465/21475) - [這個答案](http://stackoverflow.com/a/757574/21475)解釋的基本原理是避免指針被意外指定(和記憶採取所有權)沒有這個意圖。通過創建顯式的臨時對象並分配這些對象來解決這個問題。 – Cameron 2013-02-17 01:08:30

回答

6

如果你被允許這樣寫:

std::unique_ptr<int> p = new int(5); 

那麼你也將被允許寫這些:

void Func1(std::unique_ptr<int> p); 

Func1(new int(5)); 

std::unique_ptr<int> Func2() {return new int(5);} 

還是更加危險:

void Func1(std::unique_ptr<int> p); 

int *pInt = new int(5); 
Func1(pInt); //You no longer own the pointer anymore. 
delete pInt; //You're now deleting a pointer you don't own. 

這由於顯而易見的原因不可接他們不希望將裸指針隱式轉換爲唯一指針;如果你想創建一個unique_ptr,你必須明確它:Func1(std::unique_ptr<int>(pInt));現在,每個人都可以看到你將自己的所有權轉移到了函數中。

此外,它不是operator=,這將使其工作。它是unique_ptr的單參數構造函數explicit,它停止了複製初始化語法的工作。

+0

如果我們這樣做,我們不應該允許這樣做:int * p = new int(5); std :: unique_ptr temp(p); 刪除p; – user1233963 2013-02-17 01:11:59

+2

@ user1233963:那麼將無法將指針放入'unique_ptr'中。我們的目標是確保您不會意外地做到這一點,而不會在所有權轉讓所在地發現***'unique_ptr ***。由於C++的規則,這也意味着你不能使用copy-initialization(又名:'typename var = stuff;'),你必須使用直接初始化(aka:'typename var(stuff);')。 – 2013-02-17 03:31:11

2

您所指的是unique_ptr<T>的構造函數,其原始T指針是顯式。這是故意的。一個獨特的指針取得所有權,這不應該隱式發生。用戶應該明確知道何時創建,轉移和結束所有權。

在更嚴厲的世界人能想象一個unique_ptr不採取任何原料指針可言,而是隻允許直接創造所擁有的對象:

auto p = std::unique_ptr<T>::make(arg1, arg2, arg3); 
          // Calls "new T(arg1, arg2, arg3)". 
          // Not real code. 
+0

那麼爲什麼我們可以這樣做:int * p = new int(5); std :: unique_ptr temp(p); ? – user1233963 2013-02-17 01:22:29

+0

@ user1233963:因爲這是*顯式*轉換。你明確地說,「現在'temp'擁有'* p'」。 – 2013-02-17 01:23:13

+0

我仍然可以在p上調用delete並使其崩潰並燒燬。寫std :: unique_ptr p = new int(5);方式更清晰,不允許在我看來意外刪除 – user1233963 2013-02-17 01:26:03