[英]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.我使用 malloc 而不是 new 的原因是因为我在全局替换
new
使用此代码,我不希望它递归回替换。
When you do当你做
A* a = (A*) malloc(sizeof(A));
You don't actually have an A
at the location a
points to.您实际上在
a
指向的位置没有A
。 You just have enough memory allocated for an A
.您只为
A
分配了足够的内存。 What you need to do is use placement new on that pointer so that an A
object can be initialized in that memory.您需要做的是在该指针上使用放置 new,以便可以在该内存中初始化
A
对象。 That looks like那看起来像
new (a) A{};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.