[英]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();
}
这给了我
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;
^
我如何正确初始化他的互斥锁?
我使用 malloc 而不是 new 的原因是因为我在全局替换new
使用此代码,我不希望它递归回替换。
当你做
A* a = (A*) malloc(sizeof(A));
您实际上在a
指向的位置没有A
。 您只为A
分配了足够的内存。 您需要做的是在该指针上使用放置 new,以便可以在该内存中初始化A
对象。 那看起来像
new (a) A{};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.