Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ using this pointer in constructors

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.

like image 519
gilbertc Avatar asked Mar 25 '10 15:03

gilbertc


People also ask

Can I use this pointer in the constructor?

Some people feel you should not use the this pointer in a constructor because the object is not fully formed yet. However you can use this in the constructor (in the { body } and even in the initialization list) if you are careful.

Does declaring a pointer call the constructor?

ap is a pointer variable, so declaring it or assigning to it does not call any constructor.

Can I pass this in constructor C++?

The code in the constructor is really just to perform additional initialization once the object is constructed. So it is perfectly valid to use a "this" pointer in a class' constructor and assume that it points to a completely constructed object.


1 Answers

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

like image 125
David Rodríguez - dribeas Avatar answered Oct 14 '22 16:10

David Rodríguez - dribeas