This is more of a general Computer Science question than a code question exactly, but that's fine, interesting even.
Let's establish some points, and if you have any issue with these points or my subsequent reasoning, then let me know. Just to be clear, I use the word observe to kind of mean "read", and modify to kind of mean "write". This is not a formal proof.
Any number of threads may observe an object concurrently without incurring a race condition, as long as no thread concurrently modifies that object.
A const
object is modified during initialization, and not otherwise be modified during the lifetime of that object (except for destruction I suppose).
Initialization happens once during the lifetime of an object, in exactly one thread, before that object can be otherwise modified or observed (you technically can access an uninitialized object, but if you manage to pull that off a lot of things are broken regardless of thread-safety).
#2 and #3 guarantee that a const member can not be concurrently modified and observed, which is thread safe by rule #1.
Now... mutable
changes things and once you start making mutable
members, the onus is upon the class writer to make sure const
methods using mutable
members are handled in a thread-safe manner.
So, the compiler does not guarantee thread safety... but logic does guarantee thread safety. As long as an object is const
, all of its mutable
members are handled in a thread-safe manner, and all of that object's const
members observe these rules, you have a guarantee of thread safety.
The C++11 change as I understand is that where std::
objects did not previously guarantee well-behaved thread-safe const members, we now have that guarantee.
The video Herb Sutter - You don't know [blank] and [blank] is as far as I can tell the source for the claim that C++11 guarantees that const == thread-safe, and explains the claim well.