五种构造函数与两种懒汉式单例模式 复习

1.五种构造函数

class class_test1
{
public:
	class_test1();
	class_test1(const class_test1 &a);
	class_test1(class_test1 &&a)noexcept;
	class_test1& operator=(const class_test1 &a);
	class_test1& operator=(class_test1 &&a) noexcept;
private:
	int* m_val = nullptr;
};

class_test1::class_test1()
{
	m_val = new int(0);
}

class_test1::class_test1(const class_test1 & a)
{
	m_val = new int(*a.m_val);
}

class_test1::class_test1(class_test1 &&a)noexcept
{
	m_val = a.m_val;
	a.m_val = nullptr;
}

class_test1& class_test1::operator=(const class_test1& a)
{
	if (this != &a)
	{
		delete m_val;
		m_val = new int(*a.m_val);
	}
	return *this;
}

2.两种懒汉式单例模式

mutex m_lock;
class singleton
{
public:
	singleton() {}
	singleton(const singleton& s) = delete;
	singleton& operator=(const singleton& s) = delete;
	static singleton* getInstance()
	{
		if (m_self == nullptr)
		{
			m_lock.lock();
			if (m_self == nullptr)
				m_self = new singleton();  //问题在于在new中的三个函数操作的执行顺序会因为CPU的乱序性而变化
			m_lock.unlock();
		}
		return m_self;
	}
	void free()
	{
		if (m_self != nullptr)
		{
			delete m_self;
			m_self = nullptr;
		}
	}
private:
	static singleton* m_self;
};
singleton* singleton::m_self = nullptr;

//局部静态变量实现线程安全单例模式,仅C++11以上能够使用(形式简便且易于书写)
class Singleton 
{
public:
	static Singleton* GetInstance() 
	{
		//局部静态成员变量特性,当其被创建一次后不会再次创建(必须C++11以上)
		static Singleton intance;
		return &intance;
	}

	~Singleton() = default;

private:
	Singleton() = default;
	//禁用拷贝
	Singleton(const Singleton&) = delete;
	Singleton& operator=(const Singleton&) = delete;
};

int main_gouzaotest()
{
	//singleton *temp1 = singleton::getInstance();
	//singleton *temp2 = singleton::getInstance();

	Singleton *temp1 = Singleton::GetInstance();
	Singleton *temp2 = Singleton::GetInstance();

	cout << temp1 << endl;
	cout << temp2 << endl;

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

方寸间沧海桑田

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值