先来介绍一下STL的六大组件
1. 空间配置器:内存池实现小块内存分配,对应到设计模式--单例模式(工具类,提供服务,一个程序只需要一个空间配置器即可),享元模式(小块内存统一由内存池进行管理)
2.迭代器:迭代器模式,模板方法
3.容器:STL的核心之一,其他组件围绕容器进行工作:迭代器提供访问方式,空间配置器提供容器内存分配,算法对容器中数据进行处理,仿函数伪算法提供具体的策略,类型萃取 实现对自定义类型内部类型提取。保证算法覆盖性。其中涉及到的设计模式:组合模式(树形结构),门面模式(外部接口提供),适配器模式(stack,queue通过deque适配得 到),建造者模式(不同类型树的建立过程)。
4.类型萃取:基于范型编程的内部类型解析,通过typename获取。可以获取迭代器内部类型value_type,Poter,Reference等。
5.仿函数:一种类似于函数指针的可回调机制,用于算法中的决策处理。涉及:策略模式,模板方法。
6适配器:STL中的stack,queue通过双端队列deque适配实现,map,set通过RB-Tree适配实现。涉及适配器模式。
空间配置器:
一般来说,我们使用C++ new操作符主要进行两步操作:
(1)::operator new分配内存
(2)调用构造函数构造对象
而使用C++ delete操作符主要进行两步操作:
(1)调用析构函数析构对象
(2)::operator delete释放内存
STL将内存分配与对象构造析构分开,因此空间配置器分为内存分配及空间初始化。
代码实现:
#include<iostream>
#include<functional>
#include<algorithm>
#include<string>
#include<vector>
#include<map>
using namespace std;
// STL
/*
1.一级空间配置器
2.二级空间配置器
开辟的内存 大于128 一级空间配置器
malloc free
二级空间配置器
内存池
*/
/*
空间配置器
/*
1.对象的生成有几步
1.开辟空间 operator new
2.调用构造函数
2.对象的销毁
1.调用析构函数
2.释放空间 operator delete
*/
namespace LY1206
{
template<typename T>
T* _allocate(ptrdiff_t size, T*)
{
set_new_handler(0);
T* tmp = (T*)(::operator new((size_t)size*sizeof(T)));
if (tmp == NULL)
{
cout << "out of memory!" << endl;
exit(0);
}
return tmp;
}
template<typename T1, typename T2>
void _construct(T1* p, const T2& value)
{
/*
p ==> T2
*/
new (p)T2(value);
}
template<typename T>
void _deallocate(T* p)
{
::operator delete(p);
}
template<typename T>
void _destory(T* p)
{
p->~T();
}
template<typename T>
class MyAllocate
{
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<typename U>
struct rebind
{
typedef MyAllocate<U> other;
};
pointer allocate(size_type size, const void* hint = 0)
{
return _allocate(size, (pointer)0);
}
void deallocate(pointer p, size_type n)
{
_deallocate(p);
}
void construct(pointer p, const_reference val)
{
_construct(p, val);
}
void destory(pointer p)
{
_destory(p);
}
};
};
int main()
{
vector<int, LY1206::MyAllocate<int>> vec;
int arr[] = { 23, 54, 12, 31, 32, 113, 2 };
int len = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < len; ++i)
{
vec.push_back(arr[i]);
}
vector<int, LY1206::MyAllocate<int>>::iterator it = vec.begin();
for (it; it != vec.end(); ++it)
{
cout << *it << " ";
}
cout << endl;
return 0;
}
运行结果: