Phestek
Phestek

Reputation: 21

C++ - how to push objects to std::stack of std::shared_ptr?

I've got a problem with stack of shared pointers.

GameState.hpp:

class GameState : std::enable_shared_from_this<GameState>
{
public:
    virtual void update(float delta) = 0;
    virtual void render() = 0;
    virtual void handleInput() = 0;
protected:
    Game* mGame;

StatesManager.hpp:

class StatesManager
{
public:
    StatesManager();
    ~StatesManager();

    void pushState(std::shared_ptr<GameState> state);
    void changeState(std::shared_ptr<GameState> state);
    void popState();
    std::shared_ptr<GameState> peekState();
private:
    std::stack<std::shared_ptr<GameState> > mStates;
};

Here's how I'm trying to push:

statesManager.pushState(new StateSplash(this));

But that's gives me this error:

no suitable constructor exists to convert from "StateSplash *" to "std::shared_ptr<GameState>"

What's correct way of pushing object onto std::stack of std::shared_ptrs? I want to use them, because it provides "garbage collector", which I need, because if I pop element from stack when object is C-like pointer, it doesn't call destructor.

Upvotes: 2

Views: 911

Answers (1)

Lukas
Lukas

Reputation: 1305

Assuming that StateSplash is a child of GameState.

Your method accepts a std::shared_ptr and you are trying to pass a normal pointer into it. Your compiler does not know how to get from StateSplash * to std::shared_ptr<GameStage>.

You have to construct a std::shared_ptr by either

statesManager.pushState(std::make_shared<GameState>(this));

or

statesManager.pushState(std::shared_ptr<GameState>(new StateSplash(this)));

Upvotes: 3

Related Questions