c++ - 如何结合使用 std::bind 和 std::shared_ptr

标签 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 中有一个所有权的概念。

最佳答案

这个有效:

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

关于c++ - 如何结合使用 std::bind 和 std::shared_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13272831/

相关文章:

c++ - 使用二进制读写连接文件

c++ - 通过 Rcpp 正确注册插件以使用 Eigen

c++ - 在模板类中构造对象需要异常初始化

namespaces - 在 Rust 中声明多个 "use"语句是否被认为是不好的风格?

c++ - 尝试取消引用迭代器时出现段错误

c++ - 通过 setitimer 使用定时器时使用 Sleep()

c++ - 模板类的模板 friend 的问题

c++: std::bind() 'know' 模板参数是指静态函数还是成员函数?

c++ - 树中的节点是否可以接受多重继承?

binary_function 中的 C++ 段错误