11

Some C++ objects have no copy constructor, but have move constructor. For example, boost::promise. How can I bind those objects using their move constructors ?

#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;
}
4

2 回答 2

5

我不确定如何改用移动构造函数,但另一种方法是使用 boost::ref 创建对对象的可复制引用,然后您可以将它们传递给 boost::bind。

于 2010-05-14T17:13:09.427 回答
5

我看到您使用 std::move。为什么不使用应该知道移动语义的 std::bind ?

template<class F, class... BoundArgs>
unspecified bind(F&&, BoundArgs&&...);
template<class R, class F, class... BoundArgs>
unspecified bind(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 将添加移动语义接口。

您可以尝试编写 ref 并按如下方式移动

boost::function<void()> f_set_one = boost::bind(&fullfil_1, boost::ref(std::move(pi)), 1);
于 2010-05-26T10:15:57.093 回答