rvalue refs and std::move

被刻印的时光 ゝ 提交于 2019-12-03 09:00:34

In the statement:

B(B&& b)

The parameter b is declared with the type: rvalue reference to B.

In the statement:

A(b)

The expression b is an lvalue of type B.

And lvalue expressions can not bind to rvalue references: specifically the rvalue reference in the statement:

A(A&& a)

This logic follows cleanly from other parts of the language. Consider this function:

void
f(B& b1, B b2, B&& b3)
{
   g(b1);
   g(b2);
   g(b3);
}

Even though the parameters of f are all declared with different types, the expressions b1, b2 and b3 are all lvalue expressions of type B, and thus would all call the same function g, no matter how g is overloaded.

In C++11 it is more important than ever to distinguish between a variable's declaration, and the expression that results from using that variable. And expressions never have reference type. Instead they have a value category of precisely one of: lvalue, xvalue, prvalue.

The statement:

A(std::move(c))

is ok, because std::move returns an rvalue reference. The expression resulting from a function call returning an rvalue reference has value category: xvalue. And together with prvalues, xvalues are considered rvalues. And the rvalue expression of type C:

std::move(c)

will bind to the rvalue reference parameter in: A(A&& a).

I find the following diagram (originally invented by Bjarne Stroustrup) very helpful:

       expression
          /  \
    glvalue  rvalue
     /  \    /  \
lvalue  xvalue  prvalue

Because named variables are not rvalues, even when declared &&. If it has a name then its not temporary, thus you need to use std::move.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!