Reputation:
I'm overriding new()
and new[]()
operators for our heap memory manager. new()
has a mutex and is thread-safe, but I have not added a mutex to new[]()
, which works as a pass-through operator, since I suspect it will be on the stack when called. Is it correct that new[]()
will be on the stack and will not need a mutex of its own?
/*!
\brief Override the Standard C++ new [] operator
\param size [in] Number of bytes to allocate
\exception std::bad_alloc
\returns Pointer to the start of the allcoated memory block of \c size bytes
\todo Check if this is thread-safe or if it needs a mutex lock, return address probably is on the stack so it should be ok
*/
void *operator new[] (size_t size)
{
return operator new(size);
}
/*!
\brief Overrides the Standard C++ new operator
\param size [in] Number of bytes to allocate
\exception std::bad_alloc
\returns Pointer to the start of the allcoated memory block of \c size bytes
*/
void *operator new(size_t size)
{
MM_ENTER_CRITICAL_SECTION(CMemoryManager::mutex)
// Memory manager code removed since it's outside of the question context
MM_LEAVE_CRITICAL_SECTION(CMemoryManager::mutex)
}
Upvotes: 4
Views: 186
Reputation: 63250
Is it correct that new will be on the stack and will not need a mutex of its own?
Operator new[]()
works just like new()
but instead of allocating a single object, it allocates an array of objects. I don't know what that has to do with the stack, the objects allocated are allocated on the heap and a pointer to that memory is returned to you.
The only thing that's on the stack is the pointer itself, but that is the case with both versions of new
.
Seeing that new[]()
calls new()
then I don't see a reason why you'd need a mutex in new[]()
because new()
is already protected by a mutex. Any thread that calls new[]()
will have to wait if another is already inside new()
.
Upvotes: 2