c++: how to initialize std::mutex that has been allocated with malloc?

Viewed 526
// Example program
#include <mutex>

struct A {
 std::mutex m;
};

int main()
{
   A* a = (A*) malloc(sizeof(A));
   a->m = std::mutex();
}

this gives me

In function 'int main()':
11:9: error: use of deleted function 'std::mutex& std::mutex::operator=(const std::mutex&)'
In file included from 2:0:
/usr/include/c++/4.9/mutex:130:12: note: declared here
     mutex& operator=(const mutex&) = delete;
        ^

how do I properly initialize he mutex m?

The reason I'm using malloc and not new is because I'm using this code inside a global replacement of new and I don't want it to recurse back into the replacement.

1 Answers

When you do

A* a = (A*) malloc(sizeof(A));

You don't actually have an A at the location a points to. You just have enough memory allocated for an A. What you need to do is use placement new on that pointer so that an A object can be initialized in that memory. That looks like

new (a) A{};
Related