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

时间:2012-11-07 15:30:03

标签: c++ c++11 std shared-ptr stdbind

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

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中拥有占有概念。

2 个答案:

答案 0 :(得分: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();
}

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

答案 1 :(得分:7)

您是否需要动态分配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();

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

我希望有所帮助。