Loading

3.不同编译器的分配器实现

VC6编译器的实现

std::allocator实现如下:

  VC6的allocator只是以::operator new和::operator delete完成allocate()和deallocate(),没有任何特殊设计。以元素为单位,而后面有个编译器的实现是以字节为单位的。

#include <iostream>

template<class _Ty>inline 
_Ty *_Allocate(_ptrdiff_t _N, _Ty*) {
	if (_N < 0) _N = 0;
	return ((_Ty*))operator new((size_t)_N * sizeof(_Ty)));
}


template<class _Ty>
class allocator {
public:
	typedef size_t size_type;
	typedef ptrdiff_t difference_type;
	typedef _Ty *pointer;
	typedef _Ty value_type;
	pointer allocate(size_type _N, const void*) {
		return (_Allocate((difference_type)_N, (poiter)0));
	}
};

//Vc6 所有容器中的第二个默认模板参数都是allocator
template <class _Ty>
class _A = allocator<_Ty>
	class list

BC5编译分配器实现

与VC6相同,也是对operator new和operator delete封装了一次,并没有大的改进。

G2.9标准分配器实现

G2.9到了G4.9就成了标准库之外的pool_alloc。

G2.9的allocator只是以::operator new和operator delete完成allocator()和deallocator(),没有任何特殊设计。

G2.9容器使用的分配器,不是std::allocator而是std::alloc

#include <iostream>
template<class T>
class allocator {
public:
	typedef T value_type;
	typedef T* pointer;
	typedef size_t size_type;
	typedef ptrdiff_t difference_type;
	pointer allocate(size_type n) {
		return ::allocate((difference_type)n, (pointer)0);
	}
	void deallocate(pointer p) { ::deallocate(p); }
};

template <class T>
inline T* allocate(ptrdiff_t size, T*) {
	set_new_handler(0);
	T* tmp = (T*)(::operator new((size_t)(size * sizeof(T))));
	if (tmp == 0) {
		cerr << "out of memory" << std::endl;
		exit(1);
	}
	return tmp;
}

template<class T>
inline void deallocate(T* buffer) {
	::operator delete(buffer);
}

G4.9标准分配器实现

G4.9的allocator只是以::operator new和::operator delete完成allocate()和deallocate

#include <iostream>
template <typename _Tp>
class new_allocator {
	pointer allocate(size_type _n, const void* = 0) {
		if (_n > this->max_size())
			std::__throw_bad_alloc();
		return static_cast<_Tp*>(::operator new(_n * sizeof(_Tp)));
	}

	void deallocate(pointer _p, size_type) {
		::operator delete (_p);
	}
};

G2.9std::alloc运行模式

容器申请内存发生,先看看pool内有没有余量,如果有就在内存池中分配出20个链表,如果内存池中没有余量,就将剩余的内存进行碎片化处理,然后重新malloc。

posted @ 2020-01-27 08:39  三只猫-  阅读(217)  评论(0编辑  收藏  举报