【发布时间】:2014-05-13 00:56:28
【问题描述】:
我编写了以下示例代码:
#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 引用将始终引用有效对象?
【问题讨论】:
-
缓解这种情况的一种流行方法是使用智能指针。
标签: c++ reference temporary object-lifetime anonymous-objects