繁体   English   中英

std :: bad_weak_ptr,而shared_from_this

[英]std::bad_weak_ptr while shared_from_this

要创建我的EventManager,我需要创建一些函数,这些函数将使用Listeners的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;
}

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

笔记

只允许在以前共享的对象(即std :: shared_ptr管理的对象)上调用shared_from_this。 否则,该行为是不确定的(直到C ++ 17为止)(从C ++ 17起)抛出std :: bad_weak_ptr(由默认构造的weak_this的shared_ptr构造函数抛出)。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM