首页 > 其他分享 >知乎讨论:这种单例类的写法存在问题吗?

知乎讨论:这种单例类的写法存在问题吗?

时间:2022-10-20 18:35:26浏览次数:65  
标签:Singleton 知乎 getInstance int data instance 单例 写法

知乎讨论链接

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;
}


GDB调试信息截图

inst_ref1.png

标签:Singleton,知乎,getInstance,int,data,instance,单例,写法
From: https://www.cnblogs.com/ltimaginea/p/16810830.html

相关文章