samedi 1 avril 2023

Using shared_from_this in templated classes throws bad weak_ptr exception

Let say my application class is application.cpp and i have three additional classes like below

    class FooManagerCommon
          : public someObserverObserverInterface
          , public std::enable_shared_from_this<MultiAgentCapabilityManagerCommon> {
    public:
          void init(){
              m_someInstance->addObserver(shared_from_this());
          }
    };
    
    template <typename T, typename O>
    class FooCapabilityManager
          : public FooManagerCommon
          , public FooObserverInterface<O> {
    };

   class BarManager
        : public FooCapabilityManager<Bar, BarObserverInterface>
        , public std::enable_shared_from_this<BarManager> {
        static std::shared_ptr<Bar> createBar(...);
   };

my application code invokes like this in application.cpp

m_bar = BarManager::create(..);
m_bar->init();

m_bar is a std::shared_ptr<BarManager> m_bar;

but when i run the application i get a crash

__pthread_kill 0x000000018d132868
pthread_kill 0x000000018d169cec
abort 0x000000018d0a22c8
abort_message 0x000000018d122b18
demangling_terminate_handler() 0x000000018d1129f4
_objc_terminate() 0x000000018ce17774
std::__terminate(void (*)()) 0x000000018d121eb4
__cxxabiv1::failed_throw(__cxxabiv1::__cxa_exception*) 0x000000018d124c2c
__cxa_throw 0x000000018d124bd8
std::__throw_bad_weak_ptr() shared_ptr.h:141
std::shared_ptr::shared_ptr<…>(const std::weak_ptr<…> &, std::enable_if<…>::type) shared_ptr.h:1582
std::shared_ptr::shared_ptr<…>(const std::weak_ptr<…> &, std::enable_if<…>::type) shared_ptr.h:1580

Would be great if someone can provide feedback of what i might be missing here, as you can see i am enabling shared_from_this in the class and also ensuring application call init method not from the constructor.

Aucun commentaire:

Enregistrer un commentaire