【问题标题】:std::bad_weak_ptr while shared_from_thisstd::bad_weak_ptr 而 shared_from_this
【发布时间】:2017-04-06 17:10:00
【问题描述】:

要创建我的 EventManager,我需要创建函数,这些函数将使用监听器的 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 并且它从未显示,程序之前崩溃了。

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

【问题讨论】:

  • 您的演示文稿真的需要五个文件和主要文件吗?你不能把它浓缩成一个更紧凑的代表性例子吗?
  • 可能是内部弱指针直到对象创建后才更新,所以不能在构造函数中使用shared_from_this
  • 您的Game 构造函数实现调用shared_from_this 之前 任何指向该对象的共享指针存在——这是不允许的。也就是说,只有当指向this 的共享指针已经存在时,您才能调用shared_from_this
  • @KerrekSB 谢谢,当我在构造函数之外创建它时它可以工作。
  • 对于许多文件中的代码感到抱歉,我试图将它们全部放在一个文件中但失败了:c

标签: c++ c++11 shared-ptr


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    • 2015-02-26
    • 2018-06-03
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    相关资源
    最近更新 更多