我编写了以下示例代码:
#include <iostream>
class B
{
int Value;
public:
B(int V) : Value(V) {}
int GetValue(void) const { return Value;}
};
class A
{
const B& b;
public:
A(const B &ObjectB) : b(ObjectB) {}
int GetValue(void) { return b.GetValue();}
};
B b(5);
A a1(B(5));
A a2(b);
A a3(B(3));
int main(void)
{
std::cout << a1.GetValue() << std::endl;
std::cout << a2.GetValue() << std::endl;
std::cout << a3.GetValue() << std::endl;
return 0;
}
用 mingw-g++ 编译并在 Windows 7 上执行,我得到
6829289
5
1875385008
所以,我从输出中得到的是这两个匿名对象在初始化完成时被销毁,即使它们是在全局上下文中声明的。
从这个我的问题:是否存在一种方法来确保存储在类中的 const 引用将始终引用一个有效的对象?