在c ++中初始化引用并不起作用,但初始化const引用有效,为什么?

时间:2013-06-16 10:13:11

标签: c++ reference const

const string& s = "rajat";

工作时

string& s = "rajat";

没有。为什么呢?

2 个答案:

答案 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,其中还涉及终身问题。