微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 如何使用boost :: bind与非可复制的参数,例如boost :: promise?

一些C对象没有复制构造函数,但是具有移动构造函数.
例如,boost :: promise.
如何使用移动构造函数绑定这些对象?
#include <boost/thread.hpp>

void fullfil_1(boost::promise<int>& prom,int x)
{
  prom.set_value(x);
}

boost::function<void()> get_functor() 
{
  // boost::promise is not copyable,but movable
  boost::promise<int> pi;

  // compilation error
  boost::function<void()> f_set_one = boost::bind(&fullfil_1,pi,1);

  // compilation error as well
  boost::function<void()> f_set_one = boost::bind(&fullfil_1,std::move(pi),1);

  // PS. I kNow,it is possible to bind a pointer to the object instead of 
  // the object  itself. But it is weird solution,in this case I will have
  // to take cake about lifetime of the object instead of delegating that to
  // boost::bind (by moving object into boost::function object)
  //
  // weird: pi will be destroyed on leaving the scope
  boost::function<void()> f_set_one = boost::bind(&fullfil_1,boost::ref(pi),1);
  return f_set_one;
}

解决方法

我看到你使用std :: move.为什么不使用std :: bind,应该知道移动语义?
template<class F,class... BoundArgs>
unspecified bind(F&&,BoundArgs&&...);
template<class R,class F,BoundArgs&&...);

关于宣布fullfil_1的移动版本

void fullfil_1(boost::promise<int>&é prom,int x)
{
  prom.set_value(x);
}

Boost.Bind不支持移动语义(至少我不知道).我希望当前评论的Boost.Move将被接受,Boost.Bind,Boost.Lambda和Boost.Phoenix将添加移动语义界面.

您可以尝试撰写参考并移动如下

boost::function<void()> f_set_one = boost::bind(&fullfil_1,boost::ref(std::move(pi)),1);

原文地址:https://www.jb51.cc/c/113557.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐