[英]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.