我知道有些主题与此类似(例如此).
本主题中给出的示例如下:
std::string & rs1 = std::string();
Run Code Online (Sandbox Code Playgroud)
显然,std :: string()是一个右值.但是,我的问题是为什么s1合法而s2不合法?
const std::string& s1 = "String literal";
std::string& s2 = "String literal";
Run Code Online (Sandbox Code Playgroud)
该标准清楚地表明字符串文字是左值(这是可以理解的,因为它们在技术上是const char*幕后).当我编译s2时,我得到以下内容:
prog.cpp:4:19: error: invalid initialization of non-const reference of type
'std::string& {aka std::basic_string<char>&}' from an rvalue of type
'const char*' std::string& s2 = "String literal";
Run Code Online (Sandbox Code Playgroud)
我理解左值和右值的标准定义是互斥的,所以这可能是编译器的错误吗?我在这个例子中使用gcc 4.9.2.这也是文字真的是xvalue的情况之一吗?