变量的常量及其生命周期

nnd*_*wan 4 c++

所以从另一个帖子中提出的问题来看,我已经想到了一个新问题,答案对我来说并不明显.

所以看来有一个c ++规则说如果你有一个临时的const引用,那么临时的生命周期至少和const引用一样长.但是,如果你有一个本地const引用另一个对象的成员变量然后当你离开作用域时,它会调用该变量的析构函数吗?

所以这里是原始问题的修改程序:

#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;
}
Run Code Online (Sandbox Code Playgroud)

因此,当我运行此代码时,我每次都会将"嘿"作为值.这似乎意味着本地const引用不会通过生命与传入的成员对象绑定.为什么不呢?

CB *_*ley 10

b.a 不是临时的,因此它的生命周期不会受到随后绑定到它的任何引用的影响.