首先放出单例模式中的代码:
singleton.h
#ifndef SINGLETON_H
#define SINGLETON_H
#include <iostream>
#include <mutex>
class SingleTon
{
public:
static SingleTon * getInstance();
void doSomething() {
std::cout << "Do Something!" << std::endl;
}
~SingleTon() { }
private:
SingleTon() { }
static SingleTon * instance;
static std::mutex m_mutex;
class GC //这是一个嵌套类
{
public:
~GC() {
//可以在这里销毁所有的资源
if(instance != nullptr) {
std::cout << "Here destroy the instance of SingleTon!" << std::endl;
delete instance;
instance = nullptr;
}
}
static GC gc; //用于释放堆内存中创建的单例对象
};
};
#endif // SINGLETON_H
singleton.cpp
#include "singleton.h"
SingleTon *SingleTon::instance = nullptr; //在类外初始化静态对象
std::mutex SingleTon::m_mutex; //在类外初始化静态对象
SingleTon::GC SingleTon::GC::gc; //在类外初始化静态对象
SingleTon * SingleTon::getInstance() {
if(instance == nullptr) {
std::lock_guard<std::mutex> lock(m_mutex);
instance = new SingleTon();
}
return instance;
}
main.cpp
#include "singleton.h"
#include <iostream>
int main()
{
SingleTon::getInstance()->doSomething();
std::cout << "The address of SingleTon instance is: " << static_cast<void *>(SingleTon::getInstance()) << std::endl;
return 0;
}
CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
set(CMAKE_CXX_STANDARD 11)
project(1-singleton3)
file(GLOB SRC *.h *.cpp)
add_executable(${PROJECT_NAME} ${SRC})
运行结果:
Do Something!
The address of SingleTon instance is: 0x2391c20
Here destroy the instance of SingleTon!
参考资料:
https://blog.csdn.net/liang19890820/article/details/61615495#comments