std::bind と std::shared_ptr の使用を組み合わせる方法

これは動作します:

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 独自の問題もあり、おそらくラムダで終わる方がよいでしょう。

所有権を他のスレッドに渡す必要がある場合は、それも可能です:

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

ラムダは移動タイプのキャプチャをまだサポートしていないため.

お役に立てば幸いです。