下一个 C++ 标准中即将出现的 R-Value 参考是什么?

有帮助吗?

解决方案 3

这里有一个很长的 文章 来自斯蒂芬·T.拉瓦韦

其他提示

看一看为什么的C ++ 0x右值引用不默认?时,这解释了它们的实际使用相当好。

它允许你已经调用你传递到的r值或1-值的基准代码之间进行区分。例如:

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值的参考,而不是1-值(常数)参考。它被允许使用的r值的语义到数据移出在create_vector创建的临时的和推动它们到参数而不会在矢量做所有的数据中的一个昂贵的副本consume_vector

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top