class static_test
{
public:
static_test(){};
static int static_print();
private:
static int nNum;
};
int static_test::static_print()
{
printf("This is static!!\n");
return 1;
}
int static_test::nNum = static_test::static_print();
int main()
{
printf("This is main_function()!!\n");
getchar();
return 0;
}
输出
说明static变量在 main函数之前执行!
class MySingLeton
{
private:
MySingLeton(const MySingLeton& st);
MySingLeton operator = (const MySingLeton& st);
MySingLeton(){}
public:
static MySingLeton* GetInstance();
private:
static MySingLeton* pSingLeton;
};
MySingLeton* MySingLeton::pSingLeton = new MySingLeton();
MySingLeton* MySingLeton::GetInstance()
{
return pSingLeton;
}
pSingLeton在main函数初始化之前 就实例化好,不存在多线程的修改操作,读取的时候也不需要加锁,缺点是析构函数不会释放static指针,要直到程序结束!但是整体来说,我觉得这个是最好的了,一般一个工程当中的单例类也不会特别多!这么点内存开销还是可以的!