gpt4 book ai didi

c++ - std::bad_weak_ptr 而 shared_from_this

转载 作者:搜寻专家 更新时间:2023-10-31 00:28:56 25 4
gpt4 key购买 nike

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

关闭它时,程序崩溃,提示“double free or corruption”。我知道我的问题来 self 的 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;
}

游戏.h & 游戏.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

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).

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

关于c++ - std::bad_weak_ptr 而 shared_from_this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43261673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com