mardi 2 juin 2015

Singleton: how can destructor be called twice?

I asked a question about singleton implementation a few minutes ago, I've got very good answer from @LightnessRacesinOrbit.

But I cannot understand why in the next example if I instantiate Singleton in variable inst its destructor called twice?

#include <iostream>

class Singleton
{
public:
    ~Singleton()  { std::cout << "destruction!\n"; }

    static Singleton& getInstance() 
    {
        static Singleton instance;
        return instance;
    }

    void foo() { std::cout << "foo!\n"; }

private:
    Singleton() { std::cout << "construction!\n"; }
};

int main()
{
    Singleton inst = Singleton::getInstance();
    inst.foo();
}

Output:

construction!
foo!
destruction!
destruction!

Live demo

To be more correct, I understand why it is called twice. But I cannot understand how it can be called twice if after first destructor the instance of the class was destroyed? Why there is no exception?

Or it was not destroyed? Why?

Aucun commentaire:

Enregistrer un commentaire