std::bind 参数复制行为

std::bind argument copying behaviour

当异步调用函数对象时,将 std::shared_ptr 传递给 std::bind 是否安全?

即大致是以下安全:

// Copy do not reference shared_ptr
void someFunc(std::shared_ptr<Something> arg1,...other args...);

std::shared_ptr<Something> data; // This may go out of scope before the functor below is called
auto myFuture = QtConcurrent::run(std::bind(&someFunc,data,...other args...)); // In this case using QT but could be anything else

我在想,因为 std::bind 引用了它的论点,上面的内容不安全,但想确认一下。

郑重声明,我使用了两个编译器:

  1. 叮当声 7 (OS X)
  2. VC++ 12.0(即 Visual Studio 2013)

std::bind 返回的函数对象存储绑定参数的副本,因此就 data 的生命周期而言,您的代码是安全的。