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

3 c++ const pass-by-reference pass-by-value boost-ref

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)));
  }
Run Code Online (Sandbox Code Playgroud)

如果

void deliver(const chat_message& msg)
Run Code Online (Sandbox Code Playgroud)

在另一个类中通过引用获取消息然后为什么使用boost :: ref?

jua*_*nza 5

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

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