了解右值引用 [英] Understanding rvalue references
问题描述
我认为有些东西我不太了解右值引用。为什么下面的编译失败(VS2012)时出现错误'foo':无法将参数1从'int'转换为'int&&'
?
I think there's something I'm not quite understanding about rvalue references. Why does the following fail to compile (VS2012) with the error 'foo' : cannot convert parameter 1 from 'int' to 'int &&'
?
void foo(int &&) {}
void bar(int &&x) { foo(x); };
我会假设类型 int&&& c $ c>将在从bar传递到foo时被保留。为什么在函数体内部变成
int
?
我知道答案是使用 std :: forward
:
void bar(int &&x) { foo(std::forward<int>(x)); }
所以也许我没有清楚掌握 。 (另外,为什么 std :: move
?)
so maybe I just don't have a clear grasp on why. (Also, why not std::move
?)
推荐答案
I始终将lvalue记住为具有名称或可以被寻址的值。由于x有一个名称,它作为一个左值传递。引用右值的目的是允许函数以任何它认为合适的方式完全删除值。如果我们在你的例子中通过引用传递x,那么我们没有办法知道是否可以这样做:
I always remember lvalue as a value that has a name or can be addressed. Since x has a name, it is passed as an lvalue. The purpose of reference to rvalue is to allow the function to completely clobber value in any way it sees fit. If we pass x by reference as in your example, then we have no way of knowing if is safe to do this:
void foo(int &&) {}
void bar(int &&x) {
foo(x);
x.DoSomething(); // what could x be?
};
执行 foo(std :: move(x));
明确告诉编译器你完成了x,不再需要它。没有这一举动,现有代码可能会发生不良后果。 std :: move
是一个保护措施。
Doing foo(std::move(x));
is explicitly telling the compiler that you are done with x and no longer need it. Without that move, bad things could happen to existing code. The std::move
is a safeguard.
std :: forward
用于模板中的完美转发。
std::forward
is used for perfect forwarding in templates.
这篇关于了解右值引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!