【Cherno的C++视频】Singletons in C++

#include <iostream>

// Singletons in cpp are just like a way to organize a bunch of global variables and static functions
// into one kind of organized blob that is essentially under a single namespace.
// super useful for when we essentially want to have functionality that applies to some kind of
// global set of data, that we just want to potentially repeatedlly reuse.
// for example: a random number generator or a renderer.

// a basic example.
class Singleton
{
public:
	Singleton(const Singleton&) = delete;// step 2, delete the copy constructor.

	static Singleton& Get()// step 5.
	{
		return s_Instance;
	}

	void Function() {}
private:
	Singleton() {}//step 1.
	float m_Member = 0.0f;
	static Singleton s_Instance;// step 3.
};
Singleton Singleton::s_Instance;// step 4.

// useful example: a random number generator class.
class FirstRandom
{
public:
	FirstRandom(const FirstRandom&) = delete;

	static FirstRandom& Get()
	{
		return s_Instance;
	}
	//actual meat here.
	float Float() { return m_RandomGenerator; }

private:
	FirstRandom() {}
	float m_RandomGenerator = 0.5f;
	static FirstRandom s_Instance;
};
FirstRandom FirstRandom::s_Instance;

// SecondRandom: without having to call Get().
class SecondRandom
{
public:
	SecondRandom(const SecondRandom&) = delete;

	static SecondRandom& Get()
	{
		// once this function gets called for the first time it'll be instantiated, 
		// basially it's the same like FirstRandom, but looks cleaner.
		static SecondRandom s_Instance;
		return s_Instance;
	}

	static float Float() { return Get().IFloat(); }

private:
	float IFloat() { return m_RandomGenerator; }//I:internal
	SecondRandom() {}
	float m_RandomGenerator = 0.5f;
};

// singleton classes can just behave like namespaces.
namespace RandomClass {
	static float s_RandomGenerator = 0.5f;
	static float Float() { return s_RandomGenerator; }
}

int main(void)
{
	Singleton::Get().Function();
	//Singleton s = Singleton::Get();//error, copy constructor deleted.
	Singleton& s = Singleton::Get();// or auto& s = Singleton::Get();
	
	float first = FirstRandom::Get().Float();

	float second = SecondRandom::Float();

	std::cout << second << std::endl;

	std::cin.get();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值