C++ using this pointer in constructors

后端 未结 8 1077
时光取名叫无心
时光取名叫无心 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:38

    The consequence is that the thread can start and code will start executing a not yet fully initialized object. Which is bad enough in itself.

    If you are considering that 'well, it will be the last sentence in the constructor, it will be just about as constructed as it gets...' think again: you might derive from that class, and the derived object will not be constructed.

    The compiler may want to play with your code around and decide that it will reorder instructions and it might actually pass the this pointer before executing any other part of the code... multithreading is tricky

提交回复
热议问题