您的位置:首页 > 编程语言 > C语言/C++

STL之简单空间适配器实现

2015-10-11 22:56 477 查看
/* 简单的空间适配器实现
主要代码来源为 《STL源码剖析》
*/

#include<new>
#include<cstddef> //ptrdiff_t 保存两指针相减为long int ,size_t 记录大小的数据类型
#include<cstdlib> // exit()
#include<climits>//UINT_MAX
#include<iostream>// cerr 输出标准错误ostream对象

namespace mosquito
{
template <class T>
inline T* _allocate(ptrdiff_t size ,T*)//开辟空间
{
T * tmp = (T*)(::operator new ((size_t)(size * sizeof(T))));//创建一个size* sizeof(T) 大小的空间并转换为size_t类型并且把它的指针转换为T*并返回
if(tmp == 0)
{
//  cerr << " no memory " << endl;
exit(1);
}
return tmp;
}

template<class T>//销毁空间
inline void _dellocate(T* tmp)
{
::operator delete(tmp);
}

template <class T1 , class T2>
inline void _construct (T1* p ,const T2 & value)//构造
{
new(p) T1(value);//给P指针 构造一个新的T1实例  为了P-> ~T1();
}

template <class T>
inline void _destroy(T* ptr)//析构
{
ptr->~T();//显式的调用T的析构函数
}

template <class T>
class allocator{
public:
typedef T           value_type;
typedef T*          pointer;
typedef const T*    const_pointer;
typedef T&          reference;
typedef const T&    const_reference;
typedef size_t      size_type;
typedef ptrdiff_t   difference_type;

template <class M>
struct rebind{
typedef allocator<M> other;
};

pointer allocate(size_type n ,const void* hint = 0 )    //调用了_allocate来申请空间并返回指针
{
return _allocate( (difference_type)n , (pointer)0 );
}

void dellocate ( pointer p , size_type n )//调用_dellocate
{
_dellocate(p);
}

void construct( pointer p , const T& value )
{
_construct(p , value);
}

void destroy (pointer p)
{
_destroy(p);
}

pointer adderss(reference x)
{
return (pointer)&x;
}

const_pointer const_address( const_reference x )
{
return (const_pointer)&x;
}

size_type max_size() const //const限制此函数修改类成员
{
return size_type (sizeof(T));
}
};
}


此为空间适配器的简单实现,主要运用标准库new。

整个实现主要在于 _allocate(),_dellocate(),_construct(),_destory()这四个函数,类allocator是对这四个主要函数进行了封装。

新的知识:1.ptrdiff_t

2.size_t

3.placement new (new(p) T(value));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++-STL-学习 C++-STL