像全局对象这样的函数静态对象保证被销毁(假设它们被创建)。
毁灭的顺序是创造的逆序。
因此,如果一个对象在销毁期间依赖于另一个对象,您必须保证它仍然可用。这相对简单,因为您可以通过确保正确完成创建顺序来强制破坏顺序。
以下链接是关于单例的,但描述了类似的情况及其解决方案:
查找 C++ 静态初始化顺序问题
外推到常见问题解答中描述的惰性初始化全局变量的一般情况,我们可以解决这样的问题:
namespace B
{
class B { ... };
B& getInstance_Bglob;
{
static B instance_Bglob;
return instance_Bglob;;
}
B::~B()
{
A::getInstance_abc().doSomthing();
// The object abc is accessed from the destructor.
// Potential problem.
// You must guarantee that abc is destroyed after this object.
// To gurantee this you must make sure it is constructed first.
// To do this just access the object from the constructor.
}
B::B()
{
A::getInstance_abc();
// abc is now fully constructed.
// This means it was constructed before this object.
// This means it will be destroyed after this object.
// This means it is safe to use from the destructor.
}
}
namespace A
{
class A { ... };
A& getInstance_abc()
{
static A instance_abc;
return instance_abc;
}
}