下一个c ++标准即将出现什么是R值参考?
答案 0 :(得分:3)
它允许您区分调用您传递对r值或l值的引用的代码。例如:
void foo(int &x);
foo(1); // we are calling here with the r-value 1. This would be a compilation error
int x=1;
foo(x); // we are calling here with the l-value x. This is ok
通过使用r值引用,我们可以允许传递对临时数的引用,例如上面的第一个示例:
void foo(int &&x); // x is an r-value reference
foo(1); // will call the r-value version
int x=1;
foo(x); // will call the l-value version
当我们想要将创建对象的函数的返回值传递给使用该对象的另一个函数时,这会更有趣。
std::vector create_vector(); // creates and returns a new vector
void consume_vector(std::vector &&vec); // consumes the vector
consume_vector(create_vector()); // only the "move constructor" needs to be invoked, if one is defined
移动构造函数的作用类似于复制构造函数,但它被定义为采用r值引用而不是l值(const)引用。允许使用r值语义将数据移出create_vector
中创建的临时数据,并将它们推送到consume_vector
的参数中,而无需对向量中的所有数据进行昂贵的复制。
答案 1 :(得分:3)
看看Why are C++0x rvalue reference not the default?,它很好地解释了它们的实际用途。
答案 2 :(得分:1)
这是来自Stephan T. Lavavej的非常长的article
答案 3 :(得分:0)