mardi 25 mai 2021

How to remember the template type of a shared_ptr after assigning nullptr

How to remember the template type of a shared_ptr after assigning nullptr?

    #include <iostream>
#include <memory>

class Base
{
public:
    virtual std::string toString() { return "base"; }
};
class Derived1 : public Base
{
public:
    virtual std::string toString() override { return "derived1"; }    
};
class Container
{
public:
    std::shared_ptr<Base> mMember;

    template<class actualType>
    void InitializeMember()
    {
        mMember = std::make_shared<actualType>();
    }

    void PrintMember()
    {
        if (mMember)
            std::cout << mMember->toString();
    }

    void RemoveFromMemory()
    {
        mMember = nullptr;
    }
    void ReCreateInMemory()
    {
        // mMember needs to be a shared pointer to a new Derived1 object
    }
};

int main()
{
    Container container;

    // one time initialization
    container.InitializeMember<Derived1>();
    container.PrintMember();
    // ...
    container.RemoveFromMemory();

    // I need container to allocate a new derived class in mMember
    container.ReCreateInMemory();
    container.PrintMember();
}

How can I implement ReCreateInMemory(), so that main() prints "derived1" for a second time? The only time I want to pass the actual type is ONCE in the InitializeMember function. Thanks.

Aucun commentaire:

Enregistrer un commentaire