对超出范围的局部变量的C++引用



这个问题很简单,很可能需要解释引用是如何工作的,以及为什么我的理解有缺陷。

给定下面的简单代码片段:

#include <iostream>
#include <string>
struct Foo
{
std::string &ref;
Foo(std::string &bar) : ref(bar) { }
};
int main()
{
std::string s1 = "foo1";
Foo f(s1);
f.ref[0] = 'b';
std::cout << s1 << std::endl; // prints boo1
{
std::string f2("tmp");
f.ref = f2;
} 
// shouldn't f.ref be dangling by now?
std::cout << f.ref; // prints tmp
}
Output: 

我的理解是,f2将在该块的末尾被销毁,因此f.ref将是一个悬空引用。到底发生了什么?

f.ref = f2s1 = s2相同,因为f.refs1都是同一个string对象的名称。

也许您混淆了初始化引用和分配对象的概念。引用只能初始化一次(事实上,必须在创建时初始化(。

在初始化ref(bar)中,ref被初始化为指代bar所指代的相同对象(其也是与被称为s1的相同对象(。

在赋值表达式f.ref = f2;中,为f.ref命名的对象调用赋值运算符。

最新更新