所以从 a question 在另一个线程中提出的问题,我想到了一个新问题,答案对我来说并不明显。

所以似乎有一个 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;
}

所以当我运行这段代码时,我每次都会得到“嘿”作为值。这似乎意味着局部常量引用不会通过传入的成员对象在整个生命周期中将自身绑定(bind)。为什么不呢?

最佳答案

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

关于c++ - 变量的常量性及其生命周期,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10141302/

10-11 22:56
查看更多