The constness of a variable and its lifetime

c++

Solution

`b.a` is not a temporary so its lifetime is not affected by any references that are subsequently bound to it.

Problem

So from a question asked in another thread, I have thought of a new question and the answer is not obvious to me. So it appears there is a c++ rule that says if you have a const reference to a temporary, then the lifetime of the temporary is at least as long as the const reference. But what if you have a local const reference to another object's member variable and then when you leave scope - Does it call the destructor of that variable? So here is modified program from the original question: ``` #include <iostream> #include <string> using namespace std; class A { public: A(std::string l) { k = l; }; std::string get() const { return k; }; std::string k; }; class B { public: B(A a) : a(a) {} void b() { cout << a.get(); } //Has a member function A a; }; void f(const A& a) { //Gets a reference to the member function creates a const reference stores it and goes out of scope const A& temp = a; cout << "Within f(): " << temp.k << "\n"; } int main() { B b(A("hey")); cout << "Before f(): " << b.a<< "\n"; f(b.a); cout << "After f(): " << b.a.k << "\n"; return 0; } ``` So when I run this code, I get "hey" as the value everytime. Which seems to imply that a local const reference does not bind itself through life with a passed in member object. Why doesn't it?

Original source

Related problems