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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With