如何将 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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定如何使用移动构造函数,但另一种方法是使用 boost::ref 创建对对象的可复制引用,然后您可以将它们传递给 boost::bind。
I'm not sure how to use a move constructor instead, but another approach is to use boost::ref that creates copyable references to objects, and you can then pass those into boost::bind.
我看到你使用 std::move 。为什么不使用应该了解移动语义的 std::bind ?
关于声明 fullfil_1
Boost.Bind 的移动版本,Boost.Bind 还不支持移动语义(至少我不知道)。我希望目前审查的Boost.Move能够被接受,并且Boost.Bind、Boost.Lambda和Boost.Phoenix将添加移动语义接口。
您可以尝试按如下方式编写 ref 和 move
I see that you uses std::move. Why don't you use std::bind which should be aware of move semantics?
Wht about declaring a move version of fullfil_1
Boost.Bind doesn't supports move semantics yet (at least I'm not aware of). I hope that the currently reviewed Boost.Move will be accepted, and that Boost.Bind, Boost.Lambda and Boost.Phoenix will add the move semantics interfaces.
You can try composing ref and move as follows