std::bad_weak_ptr while shared_from_this
std::bad_weak_ptr while shared_from_this
要创建我的事件管理器,我需要创建函数,这些函数需要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
相关文章:
- 如何解决"invalid conversion from 'char' to 'const char*'"
- std::async from std::async in windows xp
- 引用 std::shared:ptr 以避免引用计数
- std::is_reference from std::any
- std::time_point from and to std::string
- "No suitable conversion function from 'std::string' to 'const char *' exists"
- std::chrono::time_point from std::string
- Visual accept std::string from std::byte iterator
- C++中链表的错误"Abort signal from abort(3) (sigabrt) "
- dopen():不以 root 身份运行时"failed to map segment from shared object"
- C++ 中的"template <typename From, typename Tag> struct Alias;"是什么?
- from std::vector to adept::avector
- qt get child (Callout) from QChart
- Webassembly from Javascript
- Generate boost::uuids::uuid from boost::compute::detail::sha
- 无法使用 libtool 将 -shared 参数传递给 g++
- 什么是"Reading unbounded stream from standard input (Memory Management)"的例子
- Calling C++ dll from python
- 为什么我会收到"invalid conversion from 'Queue*/Stack*' to 'int'"错误消息?
- std::chrono 在从 main 或 from 类方法使用时给出不同的值