2013-05-27 47 views
3

我只是想知道爲什麼我能夠通過所有權,而不是在以下代碼中的引用?我知道使用std::unique_ptr<car> pcar(new toyota());會讓我通過參考,但爲什麼這不適用於所有權轉讓?如何通過接口傳遞unique_ptr?

#include <memory> 

class car{}; 

class toyota : public car{}; 

void someProcess(std::unique_ptr<car> vehicle) 
{ 
    //Ownership passed. 
} 

void otherProcess(std::unique_ptr<car> const & vehicle) 
{ 
    //Reference passed. 
} 

int main(int argc, char ** argv) 
{ 
    std::unique_ptr<toyota> pcar(new toyota()); 

    someProcess(std::move(pcar)); //Allowed to pass through car interface. 

    pcar.reset(new toyota()); 

    otherProcess(pcar); //Compiler error, can't pass reference even when car interface is implemented. 

    return 0; 
} 
+1

如果您不想轉讓所有權,那麼沒有理由不將其引用作爲對象:'car const&vehicle'。 –

+0

我不認爲這是可能的。這會引發編譯器錯誤:'類型'const car'的引用無效初始化'std :: unique_ptr '的表達式'http://ideone.com/NpHfKK – Tek

+0

@Tek:Juraj(正確)評論中的想法是你先取消引用指針來獲取引用,而不是直接傳遞它。 – GManNickG

回答

3

pcar不是std::unique_ptr<car>。爲了進行編譯,需要創建一個臨時的std::unique_ptr<car>來綁定到該參數。但是你不能創建一個臨時的,因爲unique_ptr沒有(轉換)構造函數,它接受一個左值unique_ptr。

基本上,如果編譯的話,臨時會被創建,獲得指針的所有權,然後在函數返回時被銷燬,所以pcar擁有的指針將被銷燬,不是非常直觀或不期望的行爲。