C ++在构造函数中使用此指针 [英] C++ using this pointer in constructors
问题描述
在 C ++
中,在类构造函数中,我开始使用这个
指针作为参数的一个新线程在线程中广泛使用(比如说,调用成员函数)。这是坏事吗?为什么和后果是什么?
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, calling member functions). Is that a bad thing to do? Why and what are the consequences?
我的线程启动过程在构造函数的结尾。
My thread start process is at the end of the constructor.
推荐答案
结果是线程可以启动,代码将开始执行一个尚未完全初始化的对象。这本身就不够好。
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.
编译器可能想要使用你的代码,并决定它会重新排序指令,它可能实际上传递 this
指针在执行代码的任何其他部分之前...多线程是棘手的
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
这篇关于C ++在构造函数中使用此指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!