const string& s = "rajat";
工作时
string& s = "rajat";
没有。为什么呢?
答案 0 :(得分:3)
"rajat"
不是std::string
,它是由六个char
组成的以null结尾的数组,即char[6]
你可以从std::string
的以null结尾的数组构造一个char
,这就是你写的时候会发生的事情:
std::string s = "rajat";
如果要初始化string&
,则必须有string
来绑定引用,因此编译器会尝试从string
构造char
数组并将引用绑定到即
std::string& s = std::string("rajat");
然而,这是非法的,因为构造的string
是临时对象而非const引用不能绑定到临时对象,请参阅How come a non-const reference cannot bind to a temporary object?
答案 1 :(得分:2)
这将隐式地从RHS上的字符串文字构造一个临时string
。然后将临时绑定到引用:
const string& s = "rajat";
// ^^^^^ temporary string is constructed from "rajat" literal
该语言只允许const
引用绑定到临时对象,所以这个
string& s = "rajat";
是非法的,因为它试图将非const引用绑定到临时string
。
请参阅此相关GotW post,其中还涉及终身问题。