小编Tom*_*ale的帖子

Singleton析构函数不叫?

所以我写了一个简单的单例类.当我创建一个对象时,会调用构造函数,但是当它超出范围时,它的析构函数(释放对象)似乎不会被调用.

#include <iostream>

using namespace std;

class Singleton {
public:
    static Singleton &getInstance( )
    {
        if (instance == nullptr) {
            cout << "Creating instance.\n";
            instance = new Singleton();
        }
        return *instance;
    }
    static void destroyInstance( )
    {
        if (instance != nullptr) {
            cout << "Destroying instance.\n";
            delete instance;
            instance = nullptr;
        }
    }
    ~Singleton( )
    {
        if (instance != nullptr) {
            cout << "Destroying instance.\n";
            delete instance;
            instance = nullptr;
        }
    }
private:
    Singleton( ) { }

    static Singleton *instance; …
Run Code Online (Sandbox Code Playgroud)

c++

2
推荐指数
1
解决办法
823
查看次数

标签 统计

c++ ×1