为什么这个程序使用boost::ref
why is this program using 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)));
}
如果
void deliver(const chat_message& msg)
在另一个类中,通过引用获取消息,那么为什么要使用boost::ref呢?
boost::bind
会复制其输入,因此如果在这种情况下不使用boost::ref
,则会复制chat_message
。因此,代码的作者似乎希望避免这种复制(以实例化一两个boost::ref
对象为代价(。如果chat_message
很大或复制成本很高,这可能是有意义的。但是使用boost::cref
更有意义,因为原始消息是通过const引用传递的,并且调用不应该修改传递的消息。
注意:以上适用于std::bind
和std::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
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 对RValue对象调用的LValue ref限定成员函数
- boost::进程间消息队列引发错误
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- cmake如何在fedora工作站中找到boost静态库包
- 将Ref对象作为类成员
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- Boost Graph Library,修复节点大小
- 什么是"#include <boost/functional/hash.hpp> "?
- 基于boost的程序的静态链接——zlib问题
- C++:如何在CLion IDE中安装Boost
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 使用 boost::iterator_facade<> 返回迭代器的 ref,但const_ref返回 const_iterator?
- ref() in Boost::Lambda?
- 为什么这个程序使用boost::ref
- 由于删除了函数,不同的boost版本导致boost/core/ref.hpp失败
- 如何在boost中使用boost::ref.传递参数时的形参库
- 使用boost::ref传递对接受值的函数的引用
- boost::ref 没有发生匹配调用错误,但 std::ref 没有发生匹配调用错误
- 为什么 std::ref 不能用于将对象传递到 Boost.Python 模块中?