【发布时间】:2015-03-11 16:43:35
【问题描述】:
考虑以下代码:
class Foo
{
private:
const string& _bar;
public:
Foo(const string& bar)
: _bar(bar) { }
const string& GetBar() { return _bar; }
};
int main()
{
Foo foo1("Hey");
cout << foo1.GetBar() << endl;
string barString = "You";
Foo foo2(barString);
cout << foo2.GetBar() << endl;
}
当我执行这段代码时(在 VS 2013 中),foo1 实例的_bar 成员变量中有一个空字符串,而foo2 的相应成员变量包含对值“You”的引用。 为什么会这样?
更新:我当然在这个例子中使用了 std::string 类。
【问题讨论】:
-
因为第一个指向一个临时字符串,该字符串在调用 Foo 构造函数后立即被销毁。 (从 (c-)string 文字 "Hey" 创建的临时 std::string)
-
只是指出,如果你使用
const char *,第一种情况就可以了,因为字符串文字永远存在。 -
顺便说一句,如果您的构造函数采用非常量参数,第一个版本将无法编译,因为您无法将临时对象绑定到非常量引用。
-
@Borgleader 是的,我知道,这就是我将其设为 const 的原因 :-)
标签: c++ string reference pass-by-reference