I am certain that, in practice, use of ::new
is thread-safe. My question is what part of the standard provides that guarantee, if any? Is this a convention? Is this something where the standard gives implementations a lot of latitude (like the relatively loose constraints about what size each data type is) to support a wide variety of hardware?
I'm hoping that there's just a line in the C++11 standard somewhere that explicitly specifies "implementations of ::new
must be thread-safe".
I'd also love to see some standardese about the thread-safety of operator new overloads. I imagine that they would also need to be required to be thread-safe, but these functions also do not fall under the blanket guarantee that const => thread safe (in C++11).
Thanks!
The C++ standard does not outright require that
new
be thread-safe. Some implementations explicitly support building C++ code in single-threaded mode, where the C standard library, includingmalloc()
may not be thread-safe. The platforms most of us use every day do offer thread-safe allocation, of course.Even if your platform provides a thread-safe
new
, you still need to be wary if you use any libraries which implement their ownoperator new
, or if you do so yourself. It's certainly possible to write anew
which works only in a single thread--maybe even intentionally!I believe this is implicitly guaranteed by the C++11 standard. If it were not, then usage of the operator new or new expression might cause a data race, and that would not be allowed by the standard. For reference, see §17.6.5.9 Data race avoidance and also
18.6.1.4 Data races [new.delete.dataraces]
"The library versions of operator new and operator delete, user replacement versions of global operator new and operator delete, and the C standard library functions calloc, malloc, realloc, and free shall not introduce data races (1.10) as a result of concurrent calls from different threads. Calls to these functions that allocate or deallocate a particular unit of storage shall occur in a single total order, and each such deallocation call shall happen before the next allocation (if any) in this order."
Your own overrides or your own replacements for the global operators should fulfill this requirement as well.
See also this proposal N3664 "Clarifying Memory Allocation", which puts more emphasis on that matter.