samedi 26 mars 2016

static unique_ptr calls destructor twice

I use a singleton pattern which returns a reference to unique_ptr dereference. Here is the code,

#include <iostream>
using std::cout; using std::endl;
#include <memory>
using std::unique_ptr;

namespace Settings {
    class Lazy {
        Lazy() { cout << "Lazy::Lazy() " << this << endl; }
    public:
        ~Lazy() { cout << "Lazy::~Lazy() " << this << endl; }
        static Lazy &instance()
        {
            static unique_ptr<Lazy> lazy(new Lazy);
            return *lazy;
        }
    };

    Lazy &lazy()
    { return Lazy::instance(); }
}

int main()
{
    cout << "main starts!" << endl;
    auto state = Settings::lazy();
    cout << "auto state = Settings::lazy() " << &state << endl;

    cout << "main ends!" << endl;
    return 0;
}

I was expecting that the destructor of the class would call only once but although the constructor called once destructor called twice, here is the output,

main starts!
Lazy::Lazy() 0xb1ec20
auto state = Settings::lazy() 0x7ffe17ae18b8
main ends!
Lazy::~Lazy() 0x7ffe17ae18b8
Lazy::~Lazy() 0xb1ec20

why destructor called twice? And even the second call this address is different.

Aucun commentaire:

Enregistrer un commentaire