使用 std::unique_ptr<T>& 有什么好处吗?而不是 std::unique_ptr<T>?
问题描述:
使用 std::unique_ptr
代替 std::unique_ptr
有什么好处吗?例如,在函数参数中?
Are there any advantages of using std::unique_ptr<T>&
instead of std::unique_ptr<T>
? For example, in function arguments?
答
std::unique_ptr 只能移动,所以如果你通过值传递 unique_ptr 那么你不能在函数调用后提取它的内容但是如果你通过引用传递那么值可以被检索.以下是相同的示例代码:
std::unique_ptr can only be moved so if you pass unique_ptr by value then you cannot extract its contents after function call but if you pass by reference then value can be retrieved. Below is sample code for the same :
#include <iostream>
#include <memory>
void changeUniquePtrReference(std::unique_ptr<int>& upr)
{
*upr = 9;
}
void changeUniquePtrValue(std::unique_ptr<int> upv)
{
*upv = 10;
}
int main()
{
std::unique_ptr<int> p(new int);
*p =8;
std::cout<<"value of p is "<<*p<<std::endl;
changeUniquePtrReference(p);
std::cout<<"value of p is "<<*p<<std::endl;
changeUniquePtrValue(std::move(p));
std::cout<<"Memory deallocated so below line will crash.. "<<std::endl;
std::cout<<"value of p is "<<*p<<std::endl;
return 0;
}