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

Ste*_*and 11 c++ std shared-ptr stdbind c++11

我需要经常做这样的事情:

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

AsyncOperation任何自定义类实现operator() (也称为函子或函数对象).

是否可以指示std::bind使用std::shared_ptr而不是std::ref?这样可以防止内存泄漏,而不需要保持引用pAsyncOperation,并且会AsyncOperation在线程结束时自动删除,即此异步任务的结束.

编辑:我并不总是有权访问std :: thread,线程库可以是boost :: thread甚至任何其他平台相关的线程.结果,不能访问std :: async.

我的主要问题是在std :: bind中拥有一个占有概念.

Pio*_*ycz 12

这有效:

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();
}
Run Code Online (Sandbox Code Playgroud)

请参阅:http://liveworkspace.org/code/4bc81bb6c31ba7b2bdeb79ea0e02bb89


Mat*_*usz 7

你需要AsyncOperation动态分配吗?如果没有,我会这样做:

auto f = std::async([]{ AsyncOperation()(); });
f.wait();
Run Code Online (Sandbox Code Playgroud)

除此以外:

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

您当然可以使用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();
Run Code Online (Sandbox Code Playgroud)

因为lambdas还不支持移动类型捕获.

我希望有所帮助.