C++嵌套类在单例模式Singleton中自动释放堆内存的应用

首先放出单例模式中的代码:
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值