bind使用及空间配置器
一、bind的使用
template< class F, class T >
std::binder1st<F> bind1st( const F& f, const T& x );//f是一个二元函数对象
template< class F, class T >
std::binder2nd<F> bind2nd( const F& f, const T& x );//f是一个二元函数对象
template< class F, class... Args >
/*unspecified*/ bind( F&& f, Args&&... args );//f是一个n元函数(n是0到任意值)
bind可以绑定的普通函数、成员函数以及数据成员上来。
bind可以改变函数的形态
auto f = bind(add, 1, 2);//add函数是int(int, int),经过bind后变成int();
占位符:占位符本身表示形参的位置,占位符中的数字表示实参的位置。
std::placeholders::_1;
std::placeholders::_2;
二、function的使用
template< class R, class... Args >
class function<R(Args...)>
int (int)
vector<int>
函数的容器,可以存函数类型。std::bind + std::function实现多态
三、空间配置器
两级空间配置器,一级空间配置器底层使用malloc,二级空间配置器需要分类讨论,大于128时候还是使用malloc,如果小于128使用内存池+自由链表。
_Tp* allocate(size_type __n, const void* = 0)
{
return __n != 0 ? static_cast<_Tp*>(_Alloc::allocate(__n * sizeof(_Tp))) : 0;
}
typedef alloc _Alloc;
//第一个分支(一级空间配置器)
typedef malloc_alloc alloc;
typedef __malloc_alloc_template<0> malloc_alloc;
template <int __inst>
class __malloc_alloc_template
{
public;
static void* allocate(size_t __n)
{
void* __result = malloc(__n);
if (0 == __result)
__result = _S_oom_malloc(__n);
return __result;
}
};
//第二个分支(二级空间配置器)
typedef __default_alloc_template<__NODE_ALLOCATOR_THREADS, 0> alloc;
template <bool threads, int inst>
class __default_alloc_template
{
public:
enum {_ALIGN = 8};
enum {_MAX_BYTES = 128};
enum {_NFREELISTS = 16};
public:
static void* allocate(size_t __n)
{
if(__n > 128)
{
malloc(__n);//当一次申请长度大于128的时候,使用malloc
}
else
{
//16个自由链表 + 内存池
}
}
};

浙公网安备 33010602011771号