[英]Unique Pointers: LValue Reference vs RValue Reference function calls
I started using c++ std::unique_ptr
s and I stumbled across the following problem:我开始使用 c++ std::unique_ptr
s,我偶然发现了以下问题:
I want to pass a reference of my unique pointer to a function and assign a new value to the pointer in this function.我想将我的唯一指针的引用传递给 function 并为此 function 中的指针分配一个新值。 Intuitively, I think the function needs to take a lvalue
reference to be able to modify the pointer.直觉上,我认为 function 需要采用lvalue
引用才能修改指针。 But, in the following code example both options ( lvalue
reference and rvalue
reference + std::move
) do the same thing (I suppose).但是,在下面的代码示例中,两个选项( lvalue
引用和rvalue
引用 + std::move
)做同样的事情(我想)。
#include <memory>
#include <utility>
struct Widget {
Widget(int) {}
};
void reseat_RValue(std::unique_ptr<Widget>&& uniqPtr) {
auto tempUniqPtr = std::make_unique<Widget>(2003);
uniqPtr = std::move(tempUniqPtr);
}
void reseat_LValue(std::unique_ptr<Widget>& uniqPtr) {
auto tempUniqPtr = std::make_unique<Widget>(2010);
uniqPtr = std::move(tempUniqPtr);
}
int main() {
auto uniqPtr = std::make_unique<Widget>(1998);
reseat_RValue(std::move(uniqPtr)); // (1)
reseat_LValue(uniqPtr); // (2)
}
I don't really understand, what's the difference between (1)
and (2)
or rather which one I should use for my use-case.我真的不明白, (1)
和(2)
之间有什么区别,或者更确切地说,我应该将哪一个用于我的用例。 So maybe someone could explain what is going on with each of this functions and which one I should use.所以也许有人可以解释每个功能发生了什么以及我应该使用哪个功能。
Yes they do the same thing.是的,他们做同样的事情。 From your intent, ie passing-by-reference and modifying it in the function, passing-by-lvalue-reference would be better.根据您的意图,即通过引用传递并在 function 中对其进行修改,通过左值引用传递会更好。 It makes your intent more clear (as @bitmask suggested);它使您的意图更加清晰(如@bitmask 建议的那样); the function expects an lvalue and would modify it inside the function. function 需要一个左值,并将在 function 内修改它。 And for passing-by-rvalue-reference you need to use std::move
for lvalues to be passed to the function, and it allows to pass rvalues like temporaries which seems meaningless.对于按右值引用传递,您需要使用std::move
将左值传递给 function,它允许像临时变量一样传递右值,这似乎毫无意义。 eg例如
// meaningless; the temporary `std::unique_ptr` would be destroyed immediately
reseat_RValue(std::make_unique<Widget>(1998));
Actually std::unique_ptr::reset does the same thing for you in function with lvalue reference - it is simpler.实际上 std::unique_ptr::reset 在带有左值引用的 function 中为您做同样的事情 - 它更简单。 IMO, the rvalue semantics fits best for huge objects, not for pointers. IMO,右值语义最适合大对象,而不是指针。 But yes, unique_ptr uses it to achieve a sole pointer count.但是,是的,unique_ptr 使用它来实现唯一的指针计数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.