首页 > 解决方案 > 如何删除静态对象

问题描述

考虑以下代码

class Foo {
public:
    static Foo *create() {
        /*if (!_pInstance)
            _pInstance = new Foo();*/
        return _pInstance;
    }
    void print() {
        cout << "Hi there "<<this << endl;
    }
private:
    static Foo *_pInstance;
    Foo() = default;
    //~Foo() = default;
};

Foo *Foo::_pInstance = nullptr;
int main()
{
    Foo *obj1 = Foo::create();
    obj1->print();
    delete obj1;
    obj1->print();

    system("PAUSE");
    return 0;
}

我正在研究单例设计模式,但我面临着静态对象的奇怪世界。

此代码输出为:

Hi there 00000000
Hi there 00000000

为什么?我怎样才能删除这个对象?我想要一个导致该程序崩溃的解决方案。

标签: c++staticnullptr

解决方案


推荐阅读