C++ using this pointer in constructors

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

    0 讨论(0)
  • 2020-12-15 17:42

    Depends on what you do after starting the thread. If you perform initialization work after the thread has started, then it could use data that is not properly initialized.

    You can reduce the risks by using a factory method that first creates an object, then starts the thread.

    But I think the greatest flaw in the design is that, for me at least, a constructor that does more than "construction" seems quite confusing.

    0 讨论(0)
提交回复
热议问题