天天看點

五種構造函數與兩種懶漢式單例模式 複習

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

繼續閱讀