这可能是显而易见的,但我认为这对我来说有些困难。鉴于此:
void test(std::string&&) { }
std::string x{"test"};
test(std::move(x)); // ok
此代码以右值引用作为参数调用 test()
,因此程序可以按预期进行编译。
现在看看这个:
void other_test(const std::string&) { }
std::string x{"test"};
other_test(std::move(x)); // ok???
我在这里倾斜了。为什么这个版本编译? std::move
返回 && 类型;为什么我在使用 const&
的第二种方法中没有出现错误?
我知道
int&& s = 5;
const int& s = 5;
是有效的,因为在这两种情况下我都提供了没有左值的东西,它没有地址。 &&
和 const&
是等价的吗?如果没有,有区别吗?
最佳答案
简单来说:
&&
可以绑定(bind)到非常量右值(prvalues 和 xvalues)const &&
可以绑定(bind)到右值(const 和非常量)&
可以绑定(bind)到非常量左值const &
可以绑定(bind)到右值(右值和 x 值)和左值(每个都是常量和非常量)。又名对任何事情。
关于C++11 右值引用与常量引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52104649/