const 引用变量的生命周期未延长

Lifetime of const reference variable not extended

将临时变量绑定到 const 引用可延长其生命周期;比照。 GotW #88.

为什么这不适用于此代码段?直播here.

#include <iostream>
#include <string>

struct A {
    A() : s("abc") {}
    const std::string& s;
};

struct B {
    const std::string& s = "def";
};

int main() {
    A a;
    std::cout << a.s << std::endl;
    B b;
    std::cout << b.s << std::endl;
}

奖励问题:如何使用 gcc 触发警告?

生命周期仅延长至 B 的编译器生成器构造函数的末尾。当构造函数 returns 时,为保存 "def" 而创建的临时字符串将被销毁,留下悬空引用。

在您链接到的文章中,您会发现:

(Note this only applies to stack-based references. It doesn’t work for references that are members of objects.)

这就是 ab 中的引用无效的原因。它们不会延长临时工的寿命。

来自 C++14 [class.temporary]/5:

The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except:

  • A temporary bound to a reference member in a constructor’s ctor-initializer persists until the constructor exits.

  • [...]

cppreference.com 说:

a temporary bound to a reference member in a constructor initializer list persists only until the constructor exits, not as long as the object exists.

http://en.cppreference.com/w/cpp/language/reference_initialization