一个简易的allocator

#include <vector>  
#include <iostream>  
#include <algorithm>
using namespace::std;  

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

	template <class U>
	struct rebind { typedef malloc_allocator<U> other; };

	malloc_allocator() {}
	malloc_allocator(const malloc_allocator&) {}
	template <class U>

	malloc_allocator(const malloc_allocator<U>&) {}
	~malloc_allocator() {}

	pointer address(reference x) const { return &x; }

	const_pointer address(const_reference x) const 
	{
		return x;
	}

	pointer allocate(size_type n, const_pointer = 0) 
	{
		cout<<"Allocate allocate"<<endl;
		void* p = std::malloc(n * sizeof(T));
		if (!p)
			throw std::bad_alloc();
		return static_cast<pointer>(p);

	}

	void deallocate(pointer p, size_type) 
	{ 
		cout<<"Allocate deallocate"<<endl;
		std::free(p); 
	}
	size_type max_size() const {
		return static_cast<size_type>(-1) / sizeof(T);
	}

	void construct(pointer p, const value_type& x) 
	{
		cout<<"Allocate construct"<<endl;
		new(p) value_type(x);
	}
	void destroy(pointer p)
	{
		cout<<"Allocate destroy"<<endl;
		p->~value_type(); 
	}

private:

	void operator=(const malloc_allocator&);

};

template<> 
class malloc_allocator<void>
{
	typedef void value_type;
	typedef void* pointer;
	typedef const void* const_pointer;
	template <class U>
	struct rebind { typedef malloc_allocator<U> other; };
};

template <class T>
inline bool operator==(const malloc_allocator<T>&,const malloc_allocator<T>&)
{
	return true;
}

template <class T>
inline bool operator!=(const malloc_allocator<T>&,const malloc_allocator<T>&) 
{
	return false;
}

int main()  
{  
	std::vector<int, malloc_allocator<int>>myvector;
	
	myvector.push_back(1);
	
	system("pause");  
	return 0;  
}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值