【发布时间】:2015-03-08 07:32:55
【问题描述】:
我知道已经有类似的主题(例如this)。
本主题中给出的示例是这样的:
std::string & rs1 = std::string();
很明显,std::string() 是一个右值。但是,我的问题是为什么 s1 合法而 s2 不合法?
const std::string& s1 = "String literal";
std::string& s2 = "String literal";
标准明确指出字符串文字是左值(这是可以理解的,因为它们在技术上是 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";
我知道左值和右值的标准定义是互斥的,那么这可能是编译器的错误吗?我在这个例子中使用 gcc 4.9.2。这也是文字实际上是 xvalue 的情况之一吗?
【问题讨论】:
-
因为非常量左值引用不能绑定到临时对象。 const lvalues 引用即可。字符串类型的临时对象是从“const char*”创建的。这与引用绑定。
-
你确定你的示例代码是你编译的吗?
const std::string & s2 = "String literal"完全有效,而std::string & s1 = "String literal"显然不是。 -
已编辑。感谢您的快速回复。我刚刚意识到我复制/粘贴错误。
-
“字符串文字”是语言语法中的词素,而不是对象。词位表示的对象是一个字符数组,而不是
std::string类型的对象(它来自库,完全不同)。 -
@KerrekSB 这似乎含糊不清。该标准规定“尝试修改字符串文字的效果是未定义的。”,这意味着在某些上下文中字符串文字是字符数组。
标签: c++ reference language-lawyer string-literals lvalue