1

Consider the following code

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;
}

I was working on the singleton design pattern, but I faced by the static object's strange world.

This code output is:

Hi there 00000000
Hi there 00000000

Why? How I can delete this object? I wanna a solution to cause a crash in this program.

hosh0425
  • 98
  • 1
  • 10
  • You "deleted" the object pointed to by the pointer. The pointer is just equal to nullptr. So calling the non-static member function means undefined behavior. Make the pointer not equal to nullptr. – Vlad from Moscow Sep 12 '19 at 16:50
  • Vaguely related: Don't do singletons like this (Probably shouldn't do singleton at all, mind you). [Do something like this instead](https://stackoverflow.com/a/1008289/4581301) – user4581301 Sep 12 '19 at 16:52
  • Why do you want it to crash? Why not design it so it can never be `nullptr`? – Martin York Sep 12 '19 at 17:07
  • I think it is not duplicate by the mentioned question, am speaking about **static** objects, maybe this quote from Andrei Alexandrescu makes it vivid: C++ guarantees this is possible, static objects' memory lasts for the duration of the program. – hosh0425 Sep 16 '19 at 11:18

0 Answers0