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