Stream safe pass through operator

I redefine the new() and new[]() operators for our heap memory manager. new() has a mutex and is thread safe, but I did not add mutex to new[]() , which works as a pass-through statement, 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 its own mutex?

 /*! \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 outside of the question context MM_LEAVE_CRITICAL_SECTION(CMemoryManager::mutex) } 
+4
source share
1 answer

Is it right that the new one is on the stack and you donโ€™t need your own mutex?

The new[]() operator works the same as new() , but instead of selecting one object, it allocates an array of objects. I donโ€™t know what this is about the stack, selected objects are allocated on the heap, and a pointer to this memory is returned to you.

The only thing on the stack is the pointer itself, but this happens in both versions of new .

Having seen that new[]() calls new() , and then , I see no reason why you need a mutex in new[]() , because new() already protected by the mutex. Any thread that calls new[]() will have to wait if the other is already inside new() .

+2
source

All Articles