#include <iostream>
using namespace std;
class Singleton {
public:
static Singleton* GetInstance() {
// スタック上で static なインスタンスを作れば、
// NULL チェックする必要がないので、
// スレッドセーフな Singleton になる
static Singleton instance;
return &instance;
}
void Operation() {
cout << "addr: " << this << endl;
cout << "m_num: " << m_num << endl;
}
void Set(int num) {
m_num = num;
}
private:
// 生成、コピーの禁止
Singleton() : m_num(0) {}
Singleton(const Singleton& r) {}
Singleton& operator=(const Singleton& r) {}
int m_num;
};
int main() {
Singleton *obj1 = Singleton::GetInstance();
Singleton *obj2 = Singleton::GetInstance();
obj1->Operation();
obj1->Set(1);
obj2->Operation();
return 0;
}
出力
addr: 0x402018
m_num: 0
addr: 0x402018
m_num: 1
複数のインスタンスを管理する
static Singleton* GetInstance(int id) {
static map<int, Singleton*> instances;
map<int, Singleton*>::iterator it = instances.find(id);
if (it == instances.end()) {
instances[id] = new Singleton;
return instances[id];
} else {
return it->second;
}
}
参考サイト
最終更新:2012年01月27日 00:39