簡體   English   中英

如何結合使用 std::bind 和 std::shared_ptr

[英]How to combine the use of std::bind with std::shared_ptr

我需要經常做這樣的事情:

AsyncOperation * pAsyncOperation = new AsyncOperation();
auto bindOperation = std::bind(&AsyncOperation::operator(), std::ref(*pAsyncOperation));
std::thread thread(bindOperation );
thread.join();

AsyncOperation是實現operator() (也稱為函數對象)的任何自定義類。

是否可以指示std::bind使用std::shared_ptr而不是std::ref 這將防止內存泄漏,而無需保留對pAsyncOperation的引用,並且會在線程結束時自動刪除AsyncOperation ,即此異步任務的結束。

編輯:我並不總是有權訪問 std::thread,線程庫可以是 boost::thread 甚至任何其他平台相關的線程。 因此,無法訪問 std::async。

我的主要問題是在 std::bind 中有一個所有權的概念。

這有效:

struct AsyncOperation {
    void operator()()
    {
        std::cout << "AsyncOperation" << '\n';
    }
};

int main() {
  std::shared_ptr<AsyncOperation>  pAsyncOperation = std::make_shared<AsyncOperation>();
  auto bindOperation = std::bind(&AsyncOperation::operator(), pAsyncOperation);
  std::thread thread(bindOperation );
  thread.join();
}

請參閱:http: //liveworkspace.org/code/4bc81bb6c31ba7b2bdeb79ea0e02bb89

是否需要動態分配AsyncOperation 如果沒有,我會這樣做:

auto f = std::async([]{ AsyncOperation()(); });
f.wait();

除此以外:

std::unique_ptr<AsyncOperation> op(new AsyncOperation);
auto f = std::async([&]{ (*op)(); });
f.wait();

您當然可以使用std::thread ,但它會帶來更多問題(即在其他線程中進行異常處理)。 std::bind也有它自己的問題,你可能最好以 lambda 結束。

如果您確實需要將所有權傳遞給其他線程,您也可以這樣做:

std::unique_ptr<AsyncOperation> op(new AsyncOperation);
auto f = std::async([&](std::unique_ptr<AsyncOperation> op){ (*op)(); }, std::move(op));
f.wait();

因為 lambda 還不支持移動類型捕獲。

我希望這有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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