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?
boost::bind
makes a copy of its inputs, so ifboost::ref
is not used in this case, a copy of thechat_message
will be made. So it seems the authors of the code want to avoid that copy (at the cost of instantiating aboost::ref
object or two). This could make sense ifchat_message
is large or expensive to copy. But it would make more sense to use aboost::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
andstd::tr1::bind
.