技術(shù)原理:
- 私有化構(gòu)造函數(shù)席镀,析構(gòu)函數(shù)卧檐,拷貝構(gòu)造函數(shù)和賦值操作符切蟋,不讓外部構(gòu)造秸妥,并將默認函數(shù)實現(xiàn)設置為delete
- 使用std::shared_ptr管理單例內(nèi)存滚停,避免內(nèi)存泄漏
- 使用可變參數(shù)模板構(gòu)造任意對象
代碼如下
singleton.hpp
#ifndef _SINGLETON_HPP_
#define _SINGLETON_HPP_
#include <memory>
template <typename T>
using shared_ptr = typename std::shared_ptr<T>;
template <typename T>
class Singleton {
public:
template <typename ... Args>
static shared_ptr<T>& Instance(Args&& ... args) {
if(!m_pInstance) {
m_pInstance = shared_ptr<T>(new T(std::forward<Args>(args)...));
}
return m_pInstance;
}
private:
static shared_ptr<T> m_pInstance;
Singleton() = delete;
virtual ~Singleton() = delete;
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
};
template <typename T>
shared_ptr<T> Singleton<T>::m_pInstance = nullptr;
#endif
main.cpp
#include "singleton.hpp"
#include <iostream>
using std::cout;
using std::endl;
struct Person
{
Person(): m_Name("呵呵"), m_Age(20) {
}
Person(std::string name, int age): m_Name(name), m_Age(age) {}
std::string m_Name;
int m_Age;
};
struct Visitor {
Visitor(): m_Name("呵呵"), m_Age(20) {
}
std::string m_Name;
int m_Age;
};
int main(void) {
shared_ptr<int> sInt = Singleton<int>::Instance(100);
cout << *sInt << endl;
// 兩次調(diào)用都獲得 張三
cout << "Person類相關(guān)信息輸出: " << endl;
shared_ptr<Person> p = Singleton<Person>::Instance("張三", 30);
cout << "姓名: " << p->m_Name << " 年齡: " << p->m_Age << endl;
shared_ptr<Person> p2 = Singleton<Person>::Instance();
cout << "姓名: " << p2->m_Name << " 年齡: " << p2->m_Age << endl;
// 調(diào)用無參構(gòu)造函數(shù)
cout << "Visitor類相關(guān)信息輸出: " << endl;
shared_ptr<Visitor> v = Singleton<Visitor>::Instance();
cout << "姓名: " << v->m_Name << " 年齡: " << v->m_Age << endl;
}
Makefile
TAR=main
WORKSPACE_DIR=.
CC:=g++
.PHONY: build clear all
build:
$(CC) -std=c++11 $(WORKSPACE_DIR)/*.*pp -g -o $(TAR)
all: clear build
clear:
rm -rf $(TAR)
程序輸出如下
圖片.png