为什么这段代码只会执行一次构造函数 第二次和第三次会跳过构造函数
是否与函数是static和对象的类型是static有关?
singleton.h
#ifndef SINGLETON_H_
#define SINGLETON_H_
class Singleton
{
public:
static Singleton * GetTheOnlyInstance();
protected:
Singleton(){}
private:
...
};
#endif
singleton.cpp
#include "singleton.h"
Singleton * Singleton::GetTheOnlyInstance()
{
static Singleton objSingleton;
return &objSingleton;
}
调用程序 main.cpp
#include <iostream>
#include "singleton.h"
using namespace std;
int main()
{
Singleton * ps1 = Singleton::GetTheOnlyInstance();
Singleton * ps2 = Singleton::GetTheOnlyInstance();
Singleton * ps3 = Singleton::GetTheOnlyInstance();
cout << ps1 << endl << ps2 << endl << ps3 << endl;
return 0;
}
输出结果
0x6013b0
0x6013b0
0x6013b0
证明ps1、ps2、ps3是同一个地址 即同一个对象
这里用到了static关键字的两个方面: