Though standard doesn’t guarantee the thread-safety for new, most of the multi-threading operating systems support thread-safe operator new.
I am implementing my own memory management for the dynamic allocation of certain class (say MyClass) in my code. For thread safety of MyClass, I may have to use pthread or boost:: library.
I thought that if new is already thread safe then I can overload that for MyClass and leverage its safety without worrying about using those libraries.
class MyClass {
// data
public:
void* operator new (size_t);
void operator delete (void*);
};
Is it a fair assumption for C++03 systems/compilers?
Edit: Since my question is not followed by few users. I am detailing that part:
If I have 2 threads which do new int() and new int(), then 2 unique memory addresses will be returned. Now, in my overloaded MyClass::new I am not using global ::new() or any threading library; but own memory manager (which doesn’t know anything about threads). Pseudo code:
char pool[BIG_SIZE];
void* MyClass::operator new (size_t size)
{
// get some memory from 'pool' without using any thread library
return p;
}
My assumption is, since global ::new is thread safe, this overloaded operator new also should be thread-safe. In other words, compiler should be emitting thread-safety related code wherever it encounters new keyword. Is this a correct assumption ?
It is.
However note that in C++11 new is thread safe.
Of course, when you add thread unsafe code, it makes your
operator newthread unsafe.Following your edit (which changed the whole question):
The assumption that the compiler adds thread safety code around the new call is pretty wrong. Sane implementations will always add thread safety within the inner implementation of operator new (already because of efficiency considerations like per-thread memory pools).
That is, when you write a thread unsafe allocation function, just by naming it
operator newwill not magically make it thread safe, as this is just like any other function, only with a special way to be invoked.