Search code examples
c++c++11shared-ptr

std::bad_weak_ptr while shared_from_this


To create my EventManager, I needed to create functions which would take shared_ptr of Listeners to store them into vectors and call their event function. I did so, and it works correctly, unless when I close my program.

When closing it, the program crashes, saying "double free or corruption". I understood my problem came from my std::shared_ptr(this). So I tried to use shared_from_this... but it doesn't really seem to work.

main.cpp :

#include "Game.h"
#include "EventManager.h"

int main() {
    EventManager evManager;
    std::shared_ptr<Game> game(new Game(&evManager));
    return 0;
}

Game.h & Game.cpp :

#ifndef GAME_H
#define GAME_H

#include "EventManager.h"
#include <memory>

class EventManager;
class Game : public std::enable_shared_from_this<Game>
{
    public:
        Game(EventManager* evManager);
};
#endif // GAME_H

#include "Game.h"

Game::Game(EventManager* evManager) {
    evManager->addGame(shared_from_this());
}

EventManager.h & EventManager.cpp

#ifndef EVENTMANAGER_H
#define EVENTMANAGER_H

#include <memory>
#include "Game.h"

class Game;
class EventManager
{
    public:
        void addGame(std::shared_ptr<Game> game);
    protected:
        std::shared_ptr<Game> m_game;
};

#endif // EVENTMANAGER_H

#include "EventManager.h"

void EventManager::addGame(std::shared_ptr<Game> game) {
    m_game = game;
}

I executed my program with hope it would work, but I got a std::bad_weak_ptr. This error seems to occur when you try to create a shared_ptr from something that no longer exists.

So I thought it could be that the program ended too fast for the shared_ptr to create. Unfortunately it's not the problem, I added a std::cout after the creation of the Game class and it never shows, the program crashes before.

I hope you understand my problem and can help me solve it, Cheers.


Solution

  • http://en.cppreference.com/w/cpp/memory/enable_shared_from_this/shared_from_this

    Notes

    It is permitted to call shared_from_this only on a previously shared object, i.e. on an object managed by std::shared_ptr. Otherwise the behavior is undefined (until C++17)std::bad_weak_ptr is thrown (by the shared_ptr constructor from a default-constructed weak_this) (since C++17).

    you call shared_from_this in constructor when there's no shared_ptr yet