繁体   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