Const引用作为类成员

Mih*_*dor 7 c++ const reference class member

即使在这里多次讨论过这个问题,我也无法找到关于我的具体案例的确凿解释.会const延长RefTest临时的寿命吗?以下示例是合法的吗?

#include <iostream>

class RefTest
{
public:
    RefTest(const std::string &input) : str(input) {}
    ~RefTest () {std::cout << "RefTest" << std::endl;}
private:
    std::string str;
};

class Child
{
public:
    Child (const RefTest &ref) : ref_m(ref) {}
    ~Child () {std::cout << "Test" << std::endl;}
private:
    const RefTest &ref_m;
};

class Test
{
public:
    Test () : child(RefTest("child")) {}//Will the temporary get destroyed here?
    ~Test () {std::cout << "Test" << std::endl;}
private:
    const Child child;
};

int main ()
{
   Test test;
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*ely 8

参考并没有延伸寿命.代码是合法的,但只是因为你ref_m在构造函数完成后永远不会访问.

临时绑定到构造函数参数,ref.稍后绑定对它的另一个引用ref_m,不会延长生命周期.如果确实如此,那么堆栈上的对象必须持久化,只要它绑定的引用成员可以在堆上分配,因此编译器在构造函数返回时将无法展开堆栈.

获得警告会很好,但编译器并不完美,有些事情很难被警告.临时是在与绑定引用的不同上下文中创建的,因此编译器只能告诉打开onlinging或者一些聪明的静态分析存在问题.


Ale*_*aev 7

C++标准规定:

第二个上下文是引用绑定到临时的.除了下面指定的内容之外,引用绑定的临时对象或作为临时绑定对象的子对象的完整对象的临时对象的生命周期仍然存在. 绑定到构造函数的ctor-initializer(12.6.2)中的引用成员的临时绑定将持续存在,直到构造函数退出.在函数调用(5.2.2)中与引用参数的临时绑定将持续存在,直到包含该调用的完整表达式完成为止.

:顺便说一句,这是重复的(1,2),你应该寻找更好的,下一次... :)