C++ using this pointer in constructors

后端 未结 8 1115
时光取名叫无心
时光取名叫无心 2020-12-15 16:45

In C++, during a class constructor, I started a new thread with this pointer as a parameter which will be used in the thread extensively (say, call

8条回答
  •  被撕碎了的回忆
    2020-12-15 17:34

    It can be potentially dangerous.

    During construction of a base class any calls to virtual functions will not despatch to overrides in more derived classes that haven't yet been completely constructed; once the construction of the more derived classes change this changes.

    If the thread that you kick-off calls a virtual function and it is indeterminate where this happens in relation to the completion of the construction of the class then you are likely to get unpredictable behaviour; perhaps a crash.

    Without virtual functions, if the thread only uses methods and data of the parts of the class that have been constructed completely the behaviour is likely to be predictable.

提交回复
热议问题