简体   繁体   中英

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

// 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.

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{};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM