知乎讨论链接
https://www.zhihu.com/question/560947971
演示代码
#include <iostream>
#include <memory>
// version 1.3
class Singleton
{
private:
static Singleton instance;
private:
Singleton(int i) : data_(new int(i)) { }
~Singleton() { delete data_; }
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
int* data_;
public:
static Singleton& getInstance() {
return instance;
}
int* GetData()
{
return data_;
}
};
Singleton& inst_ref1 = Singleton::getInstance();
// initialize defaultly
Singleton Singleton::instance(789);
Singleton& inst_ref2 = Singleton::getInstance();
int main()
{
Singleton& inst_ref3 = Singleton::getInstance();
std::cout << *Singleton::getInstance().GetData() << std::endl;
std::cout << *inst_ref1.GetData() << std::endl;
std::cout << *inst_ref2.GetData() << std::endl;
std::cout << *inst_ref3.GetData() << std::endl;
return 0;
}