为什么这个程序使用boost::ref

why is this program using boost::ref

本文关键字:boost ref 程序 为什么      更新时间:2023-10-16

Ref库是一个小型库,用于传递对通常需要的函数模板(算法(的引用他们论点的副本。

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

在呼叫传递-

  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)));
  }

如果

void deliver(const chat_message& msg)

在另一个类中,通过引用获取消息,那么为什么要使用boost::ref呢?

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

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

bind take的参数由返回的函数对象。例如,在以下代码中:

int i=5;

bind(f,i,_1(;i值的副本存储到函数中对象boost::ref和boost::cref可用于生成函数对象存储对对象的引用,而不是副本:

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