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?
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; }
Link does not extend service life. The code is legal, but only because you never access ref_mafter the constructor completes.
ref_m
ref. , ref_m, . , , , , , .
ref
, , . , , .
++:
- . , , , , , , . ctor-initializer (12.6.2) . A (5.2.2) , .
. , , (1, 2), , ...:)