11

一部の 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;
}
4

2 に答える 2

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 に答える
5

代わりにムーブ コンストラクターを使用する方法はわかりませんが、別のアプローチとして、オブジェクトへのコピー可能な参照を作成する boost::ref を使用し、それらを boost::bind に渡すことができます。

于 2010-05-14T17:13:09.427 に答える