【问题标题】:std::bind argument copying behaviourstd::bind 参数复制行为
【发布时间】:2016-04-04 06:15:00
【问题描述】:

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

I.E.大致如下安全:

// 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. clang 7 (OS X)
  2. VC++ 12.0(即 Visual Studio 2013)

【问题讨论】:

  • 为什么std::bind 接受它的参数很重要?当然,重要的是它是否将它们的副本放入它返回的东西中,而不是如何获取它们。
  • 好点。代表我的措辞很糟糕。我担心的是返回的函子是否保留了副本或引用,T.C.在下面得到了很好的回答。

标签: c++ c++11 stdbind


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    • 1970-01-01
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    相关资源
    最近更新 更多