c++ bad_weak_ptr error

前端 未结 2 1998
无人及你
无人及你 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条回答
  •  情书的邮戳
    2021-02-05 17:33

    Before calling shared_from_this() your class needs to be stored in a shared_ptr. This means that you cannot call shared_from_this() inside the constructor, because the line the object won't be placed into the shared_ptr until after the constructor is finished.

    This is the reason that classes which use enable_shared_from_this typically have a start function which does the final steps of initialization that require the use of shared_from_this(). That start function needs to be called after the object is completely constructed, and so cannot be called from inside the constructor as you are doing.

提交回复
热议问题