lundi 26 juin 2017

Shared pointer member construction seems to call destructor

I have written two classes that are laid out below. My question is: why is the MyObj destructor getting called before the "I WANT TO ACCESS..." printout? I thought it may have been related to the use of an initialization list, but changing that didn't a difference. It seems to me that this is a quirk of the std::make_shared<T>() constructor that I'm overlooking.

Can someone explain what's happening and how to avoid it?

Is it that shared pointers are not meant for member variable usage? If so, how does one acquire the shared pointer to an instance? I want to be able to pass pointers to this member variable to a few different objects.

#include <memory> // for shared_ptr
#include <iostream> // for stdout
#include <string> // for ...string

class MyObj
{
    private:
        std::string _name;
    public:
        typedef std::shared_ptr<MyObj> shared_ptr;

        MyObj(const std::string &name) : _name(name) {}
        ~MyObj()
        {
            std::cout << "CLOSED!" << std::endl;
        }
};

class MyClass
{
    private:
        MyObj::shared_ptr _obj;
    public:
        MyClass(const std::string &name) : 
            _obj(std::make_shared<MyObj>(name)) {}

};

When I execute this code:

int main()
{
    MyClass mine("Bob");
    std::cout << "I WANT TO ACCESS BOB HERE" << std::endl;
    return 0;
}

The output to the console is

CLOSED!
I WANT TO ACCESS BOB HERE

What I want to see is:

I WANT TO ACCESS BOB HERE
CLOSED!

Aucun commentaire:

Enregistrer un commentaire