簡體   English   中英

c ++:如何初始化已使用malloc分配的std :: mutex?

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM