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();
}
- GCC 是给出编译错误
std::string&
的好方法:从临时类型的非 const 类型引用的无效初始化std::string
- VS2008 还不错,因为至少它给出了一个编译警告:警告 C4239:使用了非标准扩展:'initializing':从转换
std::string
为非std::string &
const 引用只能绑定到左值 - 问题来了 - VS2010(SP1) 编译良好,没有任何错误或警告,为什么??!!我知道VS2010 中的右值引用可用于与右值绑定,但我没有使用
&&
,而是在演示代码中,我只是使用非 const 左值引用!
有人能帮我解释一下这里 VS2010 的行为吗?它是一个错误!?谢谢