why is this program using boost::ref

3.6k views Asked by At

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?

2

There are 2 answers

1
juanchopanza On BEST ANSWER

boost::bind makes a copy of its inputs, so if boost::ref is not used in this case, a copy of the chat_message will be made. So it seems the authors of the code want to avoid that copy (at the cost of instantiating a boost::ref object or two). This could make sense if chat_message is large or expensive to copy. But it would make more sense to use a boost::cref, since the original is passed by const reference, and the call should not modify the passed message.

Note: the above applies to std::bind and std::tr1::bind.

0
AudioBubble On

The arguments that bind takes are copied and held internally by the returned function object. For example, in the following code:

int i = 5;

bind(f, i, _1); a copy of the value of i is stored into the function object. boost::ref and boost::cref can be used to make the function object store a reference to an object, rather than a copy:

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