Constant as a member of the class

Even if the topic has been discussed here many times, I cannot find a convincing explanation regarding my specific case. Will constextend the life RefTesttime temporary? Is the following example legal?

#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;
}
+5
source share
2 answers

Link does not extend service life. The code is legal, but only because you never access ref_mafter the constructor completes.

ref. , ref_m, . , , , , , .

, , . , , .

+5

++:

- . , , , , , , . ctor-initializer (12.6.2) . A (5.2.2) , .

. , , (1, 2), , ...:)

+3

All Articles