从我读过和看过的内容来看,你不能将一个rvalue的表达式绑定到左值引用.然而,我所看到的是你可以将rvalue绑定到rvalue引用,并且由于命名的rvalue引用本质上是一个左值,你可以将它绑定到左值引用.禁止将右值绑定到左值引用的原因是什么.它是出于优化目的吗?
举个例子:
#include <iostream>
using std::cout;
void bar ( int& b ) {
cout << "bar " << b << "\n";
b = 3;
}
void foo ( int&& a ) {
cout << a << "\n";
bar(a);
cout << a << "\n";
}
int main ( int argc, char ** argv ) {
foo(1);
}
Run Code Online (Sandbox Code Playgroud) string foo() { return "hello"; }
int main()
{
//below should be illegal for binding a non-const (lvalue) reference to a rvalue
string& tem = foo();
//below should be the correct one as only const reference can be bind to rvalue(most important const)
const string& constTem = foo();
}
Run Code Online (Sandbox Code Playgroud)
std::string&从类型的临时类型无效初始化类型的非const引用std::stringstd::string到std::string &非const引用可以仅被绑定到一个左值&&,而是在演示代码中,我只是使用非const左值引用!可以用somone帮我解释一下VS2010的行为吗?这是一个错误!?谢谢
我编译时,以下代码在Linux上引发错误g++ test.cpp:
#include <iostream>
using namespace std;
class A
{
public:
A(){
cout << "call A()" << endl;
};
A& operator = (const A& a) {
cout << "call operator =" << endl;
return *this;
}
A(A& a) {
cout << "call A(A& a)" << endl;
}
};
A operator - (A& a1, A& a2)
{
cout << "call operate -" << endl;
return a1;
}
int main()
{
A a1;
A a2;
A a3 = a1 - …Run Code Online (Sandbox Code Playgroud)