码迷,mamicode.com
首页 > 其他好文 > 详细

boost::ref

时间:2015-03-02 16:40:44      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

在C++的算法和函数之间,以类对象作为参数的情况很非常常见的问题,一般情况下传值语义是可行的,但也有很多特殊情况,作为参数的函数对象拷贝代价过高(具有复杂的内部状态),或者不希望拷贝对象(内部状态不应该被改变),甚至拷贝是不可行的(noncopyable、单件)。

    boost.ref应用代理模式,引入对象引用的包装器概念解决这个问题。它位于名字空间boost,为了使用ref组件 

http://www.boost.org/doc/libs/1_57_0/libs/core/doc/html/core/ref.html

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. It defines the class templateboost::reference_wrapper<T>, two functions boost::ref and boost::cref that return instances of boost::reference_wrapper<T>, a function boost::unwrap_ref that unwraps a boost::reference_wrapper<T> or returns a reference to any other type of object, and the two traits classes boost::is_reference_wrapper<T> and boost::unwrap_reference<T>.

The purpose of boost::reference_wrapper<T> is to contain a reference to an object of type T. It is primarily used to "feed" references to function templates (algorithms) that take their parameter by value.

To support this usage, boost::reference_wrapper<T> provides an implicit conversion to T&. This usually allows the function templates to work on references unmodified.

boost::reference_wrapper<T> is both CopyConstructible and Assignable (ordinary references are not Assignable).

The expression boost::ref(x) returns a boost::reference_wrapper<X>(x) where X is the type of x. Similarly, boost::cref(x) returns a boost::reference_wrapper<const>(x).

The expression boost::unwrap_ref(x) returns a boost::unwrap_reference<X>::type& where X is the type of x.

The expression boost::is_reference_wrapper<T>::value is true if T is a reference_wrapper, and false otherwise.

The type-expression boost::unwrap_reference<T>::type is T::type if T is a reference_wrapperT otherwise.

Reference

namespace boost {
  template<typename T> class reference_wrapper;

  template<typename T> struct is_reference_wrapper;
  template<typename T> struct unwrap_reference;
  template<typename T> reference_wrapper< T > const ref(T &);
  template<typename T> reference_wrapper< T const  > const cref(T const &);
  template<typename T> void ref(T const &&);
  template<typename T> void cref(T const &&);
  template<typename T> unwrap_reference< T >::type & unwrap_ref(T &);
}


http://blog.csdn.net/zengraoli/article/details/9663057
http://www.cnblogs.com/rocketfan/archive/2010/12/28/1918529.html

boost::ref

标签:

原文地址:http://www.cnblogs.com/youxin/p/4308826.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!