最近我碰到了C++的Singleton设计模式的实现/实现.看起来像这样(我从现实生活中采用了它):
// a lot of methods are omitted here
class Singleton
{
public:
static Singleton* getInstance( );
~Singleton( );
private:
Singleton( );
static Singleton* instance;
};
Run Code Online (Sandbox Code Playgroud)
从这个声明我可以推断出实例字段是在堆上启动的.这意味着存在内存分配.对我来说完全不清楚的是,什么时候内存将被解除分配?还是有漏洞和内存泄漏?好像在实施中存在问题.
我的主要问题是,如何以正确的方式实施它?
如果变量声明为static在函数的作用域中,则仅初始化一次并在函数调用之间保留其值.它的生命到底是什么?它的构造函数和析构函数何时被调用?
void foo()
{
static string plonk = "When will I die?";
}
Run Code Online (Sandbox Code Playgroud) 我试图找到一种确保静态变量的构造和销毁顺序的好方法。据我所知,静态变量的构造和销毁方式如下:
如果静态变量在不同的文件中被定义为全局空间,那么它们的构造顺序是无法保证的。
但是,如果在函数中定义了静态变量,则在第一次执行达到其声明时构造局部静态变量。
基于上面的规则,我写了下面的c++代码来确保静态变量b总是在静态变量之前被破坏a,在我的实验中保证了构造顺序和破坏顺序:
在档案啊
class A {
public:
SomeClass* GetStatic() {
static SomeClass a;
return &a;
}
}
Run Code Online (Sandbox Code Playgroud)
在文件 Bh 中:
#include "A.h"
class B {
public:
AnotherClass* GetStatic() {
A::GetStatic(); // a dummy call to force the static local variable in
// A::GetStatic() get initialized before the b.
static AnotherClass b;
return &b;
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,我A::GetStatic();在static AnotherClass b;. 如果规则 3 成立,这确保a在 之前初始化b。并且由于规则 …