std::bad_weak_ptr while shared_from_this

std::bad_weak_ptr while shared_from_this

本文关键字:from shared this while weak bad std ptr      更新时间:2023-10-16

要创建我的事件管理器,我需要创建函数,这些函数需要shared_ptr的侦听器将它们存储到向量中并调用其事件函数。 我这样做了,它工作正常,除非我关闭程序。

关闭它时,程序崩溃,显示"双重释放或损坏"。我知道我的问题来自我的std::shared_ptr(这个)。所以我尝试使用shared_from_this...但它似乎并不真正起作用。

主要.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;
}

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

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

我希望你理解我的问题,可以帮助我解决它, 干杯。

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_ptr时,您在构造函数中调用shared_from_this