c++ constructors and concurrency

c++, concurrency, constructor

Solution

Not in my experience. It is the code that calls the constructor, implicitly or otherwise, which needs to be made thread-safe should the application require it.

The rationale is that only one thread should be initializing an object at a time, so no synchronization is necessary to protect the object being initialized within the constructor itself (if the object hasn't finished initialization, it shouldn't be shared between threads anyway).

Another way to look at it is this: Objects are to be treated as logically nonexistent until their constructors have returned. So, a thread that is in the process of creating an object is the only thread that "knows" about it.

Of course, proper synchronization rules apply to any shared resource the constructor itself accesses, but that applies to any function (I've encountered people that fail to realize this, believing constructors are special and somehow provide exclusive access to all resources).

Problem

I've been thinking about writing a container class to control access to a complex data structure that will have use in a multi-threaded environment. And then the question occurred to me: Is there ever a situation where c++ constructors must be thread-safe?

Original source