c++ bad_weak_ptr error

前端 未结 2 2036
无人及你
无人及你 2021-02-05 17:11

I want to create some Timer class, which prints \"text\" every N seconds, where N will be initialized in constructor.

#include 

        
2条回答
  •  萌比男神i
    2021-02-05 17:47

    The problem is most probably that you cannot use shared_from_this until the object is actually managed by a shared pointer. In general it is not a good idea to launch a thread or asynchronous service in the constructor, as you might be unlucky and the new thread might start before the constructor has completed and thus execute on a not fully constructed object.

    In your particular case it is even worse, as you are entering the event loop inside the constructor of your Timer class, and that means that control never returns to main, the object is never managed by the shared_ptr in main...

    You should move the call to start and the call to run() to a different function, and call that from main after the object is actually managed in the shared_ptr.

提交回复
热议问题