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

问题描述 投票:0回答:1

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

给出下面的简单代码段:

#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将是一个悬空的引用。到底是怎么回事?

c++
1个回答
1
投票

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

也许您正在混淆引用的初始化和对象分配的概念。

在初始化ref(bar)中,将ref初始化为引用bar所引用的同一对象(也与称为s1的对象相同)。

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

© www.soinside.com 2019 - 2024. All rights reserved.