std :: bad_weak_ptr而shared_from_this

Meg*_*owa 3 c++ shared-ptr c++11

要创建我的EventManager,我需要创建一些函数,这些函数将使Listener的shared_ptr将它们存储到向量中并调用它们的事件函数.我这样做了,它工作正常,除非我关闭我的程序.

关闭它时,程序崩溃,说"双重免费或腐败".我知道我的问题来自我的std :: shared_ptr(this).所以我尝试使用shared_from_this ...但它似乎并没有真正起作用.

main.cpp:

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

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

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
Run Code Online (Sandbox Code Playgroud)
#include "Game.h"

Game::Game(EventManager* evManager) {
    evManager->addGame(shared_from_this());
}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)
#include "EventManager.h"

void EventManager::addGame(std::shared_ptr<Game> game) {
    m_game = game;
}
Run Code Online (Sandbox Code Playgroud)

我执行我的程序希望它能工作,但我有一个std :: bad_weak_ptr.当您尝试从不再存在的内容创建shared_ptr时,似乎会发生此错误.

所以我认为可能是程序结束得太快,无法创建shared_ptr.不幸的是,这不是问题,我在创建Game类之后添加了一个std :: cout并且它从未显示,程序崩溃之前.

我希望你能理解我的问题并帮助我解决它,干杯.

And*_*hko 5

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

笔记

允许仅在先前共享的对象上调用shared_from_this,即在由std :: shared_ptr管理的对象上.否则行为是未定义的(直到C++ 17)抛出std :: bad_weak_ptr(由默认构造的weak_this中的shared_ptr构造函数)(因为C++ 17).

shared_from_this当没有shared_ptr时,你在构造函数中调用