一个非常简单的问题,很可能需要解释引用如何工作以及为什么我的理解有缺陷。
给出下面的简单代码段:
#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 = f2
与s1 = s2
相同,因为f.ref
和s1
都是同一个string
对象的名称。
也许您正在混淆引用的初始化和对象分配的概念。
在初始化ref(bar)
中,将ref
初始化为引用bar
所引用的同一对象(也与称为s1
的对象相同)。
在赋值表达式f.ref = f2;
中,为f.ref
命名的对象调用赋值运算符。