如何通过接口传递unique_ptr?
问题描述:
我只是想知道为什么我能够通过所有权,而不是在以下代码中的引用?我知道使用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;
}
答
pcar不是std::unique_ptr<car>
。为了进行编译,需要创建一个临时的std::unique_ptr<car>
来绑定到该参数。但是你不能创建一个临时的,因为unique_ptr没有(转换)构造函数,它接受一个左值unique_ptr。
基本上,如果编译的话,临时会被创建,获得指针的所有权,然后在函数返回时被销毁,所以pcar拥有的指针将被销毁,不是非常直观或不期望的行为。
如果您不想转让所有权,那么没有理由不将其引用作为对象:'car const&vehicle'。 –
我不认为这是可能的。这会引发编译器错误:'类型'const car'的引用无效初始化'std :: unique_ptr'的表达式'http://ideone.com/NpHfKK –
Tek
@Tek:Juraj(正确)评论中的想法是你先取消引用指针来获取引用,而不是直接传递它。 – GManNickG