前言
本次笔记记录如下知识点
- 工具类ref
- 函数适配器bind
- 智能函数指针function
一、工具类ref
1、工具类ref作用介绍
- ref用于包装一个对象,使其看起来像别名一样。在传递参数时消除对象拷贝的代码,还可以利用它将不可拷贝的对象变为可以拷贝。
2、类摘要
- ref库定义了一个很小,很简单的引用类型的包装器,名字叫reference_wrapper
template<class T>
class reference_wrapper
{
public:
//构造函数
explicit reference_wrapper(T& t) : t_(&t) {
}
//隐式转型
operator T& () const {
return *t_; }
//访问被包装的对象
T& get() const {
return *t_; }
//
T* get_pointer() const {
return t_; }
private:
T* t_; //保存对象指针
};
3、基本用法
#include <stdio.h>
#include <typeinfo>
#include <set>
#include <boost/ref.hpp>
using namespace boost;
using namespace std;
int main()
{
//1、reference_wrapper的基本用法
int x = 10;
boost::reference_wrapper<int> rw1(x);
if (x == rw1)
{
printf("相同\n");
}
(int &)rw1 = 100;
boost::reference_wrapper<int> rw2(rw1);
printf("rw2 值为 = %d\n", rw2.get());
//2、使用工厂函数进行封装 ref() 获取的类型是 T ,cref() 获取的类型是T const。
double y = 2.34533;
auto rw3 = boost::ref(x);
printf("rw3 的类型为:%s\n", typeid(rw3).name());
char* str;
auto rw4 = boost::cref(str);
printf("rw4 的类型为:%s\n", typeid(rw4).name());
//3、判断T是否被包装(is_reference_wrapper(T)),解包装(unwrap_ref)
set<int> vec;
auto rw5 = boost::cref(vec);
printf("size = %d", unwrap_ref(rw5).size());
return 0;
}
运行结果如下
4、应用场景
- 假设有一个内部很复杂类big_class,用它进行拷贝,构造需要花费很大的代码,如果这时要将该类的对象当做参数进行传递,那么调用的拷贝函数和构造函数就会产生很大的代价。
- 具体代码如下:
#include <iostream>
#include <typeinfo>
#include <set>
#include <boost/ref.hpp>
using namespace boost;
using namespace std;
//一个具有复杂的内部状态的类,这里当做例子简化内部
class big_class
{
private:
int x;
public:
big_class() :