3

The Ref library is a small library that is useful for passing references to function templates (algorithms) that would usually take copies of their arguments.

from http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/example/chat/chat_server.cpp

in call deliver -

  void deliver(const chat_message& msg)
  {
    recent_msgs_.push_back(msg);
    while (recent_msgs_.size() > max_recent_msgs)
      recent_msgs_.pop_front();

    std::for_each(participants_.begin(), participants_.end(),
        boost::bind(&chat_participant::deliver, _1, boost::ref(msg)));
  }

if the

void deliver(const chat_message& msg)

in another class is taking message by reference then why is boost::ref used at all?

4

2 回答 2

5

boost::bind制作其输入的副本,因此如果boost::ref在这种情况下不使用,chat_message则会制作 的副本。因此,代码的作者似乎希望避免该副本(以实例化一个boost::ref或两个对象为代价)。chat_message如果复制量大或复制成本高,这可能是有意义的。但是使用 a 会更有意义boost::cref,因为原始是通过 const 引用传递的,并且调用不应修改传递的消息。

注意:以上适用于std::bindstd::tr1::bind

于 2013-05-29T07:09:48.787 回答
0

bind 接受的参数由返回的函数对象在内部复制和保存。例如,在以下代码中:

诠释 i = 5;

绑定(f,我,_1);i 的值的副本存储到函数对象中。boost::ref 和 boost::cref 可用于使函数对象存储对对象的引用,而不是副本:

来自http://www.boost.org/doc/libs/1_53_0/libs/bind/bind.html

于 2013-05-29T07:14:55.513 回答