C++巢狀類在單例模式Singleton中自動釋放堆記憶體的應用
阿新 • • 發佈:2018-12-20
首先放出單例模式中的程式碼:
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!