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;
}
如果您不想轉讓所有權,那麼沒有理由不將其引用作爲對象:'car const&vehicle'。 –
我不認爲這是可能的。這會引發編譯器錯誤:'類型'const car'的引用無效初始化'std :: unique_ptr'的表達式'http://ideone.com/NpHfKK –
Tek
@Tek:Juraj(正確)評論中的想法是你先取消引用指針來獲取引用,而不是直接傳遞它。 – GManNickG