参考链接:C++new和delete实现原理
VC++中
//newop2.cpp VC中new操作符的源码// newop2 Operator new(size_t, const nothrow_t&) for Microsoft C++#include <cstdlib>#include <new>_C_LIB_DECLint _callnewh(size_t size);_END_C_LIB_DECLvoid *operator new(size_t size, const std::nothrow_t&) _THROW0() { // try to allocate size bytes void *p; while ((p = malloc(size)) == 0) { // buy more memory or return null pointer _TRY_BEGIN if (_callnewh(size) == 0) break; _CATCH(std::bad_alloc) return (0); _CATCH_END } return (p); }由上述源码可以看到,new是调用了系统函数malloc来分配的内存
//VC中allocator的部分源码 <xmemory>template<class _Ty> class allocator {public: typedef _SIZT size_type; typedef _PDFT difference_type; typedef _Ty _FARQ *pointer; typedef const _Ty _FARQ *const_pointer; typedef _Ty _FARQ& reference; typedef const _Ty _FARQ& const_reference; typedef _Ty value_type; pointer address(reference _X) const {return (&_X); } const_pointer address(const_reference _X) const {return (&_X); } pointer allocate(size_type _N, const void *) {return (_Allocate((difference_type)_N, (pointer)0)); } }; template<class _Ty> inline _Ty _FARQ *_Allocate(_PDFT _N, _Ty _FARQ *) {if (_N < 0) _N = 0; return ((_Ty _FARQ *)operator new( (_SIZT)_N * sizeof (_Ty))); }由上述源码可知,VC的分配器是调用的_Allocate模板函数来分配内存,_Allocate是调用的operator new,new是调用的malloc系统函数分配的 可知VC的分配器并没有什么特殊处理
int *p = allocator<int>().allocate(512, *int*)0);allocator<int>().deallocate(p, 512);在GUN4.5中有两种分配器,一个是allocator,跟VC的一样;另一个叫_pool_alloc,这个分配器会有一个整的内存池,由16个指针组成,每个指针指向不同大小的内存,根据每次申请的大小分配那个指针上的内存,这样就避免了每次申请内存时,所带来的额外消耗,例如记录当前分配的内存大小,开始结束的标志。 第二种的用法,认为指定分配器
vector<string, __gun_cxx::__pool_alloc<string>> vec;Gnu2.9 —> Gnu4.9 自行体会
链接:iterator_traits 19: 迭代器特性-iterator traits 我认为traints是容器跟算法中间的桥梁,因为容器是多种多样的,但是在实现某种功能是,会使用同一种算法,此时,算法就需要根据各个容器的特性来进行不同的计算 那算法怎么知道各个容器的特征的呢?通过Traits
所以在每个Itreator中,都规定需要定义一下五种typedeftemplate<typename _Tp>struct _List_iterator{ typedef std::bidirectional_iterator_tag iterator_category; //容器的类别 typedef _Tp value_type; //容器的元素的类型 typedef _Tp* pointer; typedef _Tp& reference; typedef ptrdiff_t difference_type; //位置差类型};如果仅仅是重命名,直接在iterator中定义就好了,为什么还要有一个Traits呢?这是为了一个情况,就是iterator不是一个类;而是一个指针,那算法在调用一个指针作为参数的时候,就没有办法获得他的value_type,pointer,difference_type等特征所以,就抽了一个中间层,利用模板的偏特化的特性来进行一层包装//以value_type 为例 给出示例template <class I>struct iterator_traits { //如果I是class iterator,就进这里 typedef typename I::value_type value_type;};template <class T>struct iterator_traits<T*> { typedef T value;};template <class T>struct iterator_traits<const T*>{ typedef T value_type; };//为什么const T* 的value_type不是const的,因为声明一种无法被赋值的变量没什么用,没办法被算法调用并进行计算template <typename T, ...>void algorithm(...) { typename iterator_traits<T>::value_type v1;}新闻热点
疑难解答
图片精选