c++ - std::bad_weak_ptr while shared_from_this -


to create eventmanager, needed create functions take shared_ptr of listeners store them vectors , call event function. did so, , works correctly, unless when close program.

when closing it, program crashes, saying "double free or corruption". understood problem came std::shared_ptr(this). tried use shared_from_this... doesn't seem work.

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; } 

i executed program hope work, got std::bad_weak_ptr. error seems occur when try create shared_ptr no longer exists.

so thought program ended fast shared_ptr create. unfortunately it's not problem, added std::cout after creation of game class , never shows, program crashes before.

i hope understand problem , can me solve it, cheers.

http://en.cppreference.com/w/cpp/memory/enable_shared_from_this/shared_from_this

notes

it permitted call shared_from_this on shared object, i.e. on object managed std::shared_ptr. otherwise behavior undefined (until c++17)std::bad_weak_ptr thrown (by shared_ptr constructor default-constructed weak_this) (since c++17).

you call shared_from_this in constructor when there's no shared_ptr yet


Comments

Popular posts from this blog

inversion of control - Autofac named registration constructor injection -

verilog - Systemverilog dynamic casting issues -

ios - Change Storyboard View using Seague -