//#ifndef GRAVELALLOC_H_INCLUDED
//#define GRAVELALLOC_H_INCLUDED
#ifndef _GravelALLOC_
#define _GravelALLOC_
#include <new> // for placement new
#include <cstddef> // for ptrdiff_t, size_t ???
#include <cstdlib> //for exit()
#include <climits> //for UINT_MAX
#include <iostream> // for cerr
using namespace std;
namespace Gravel{
template <class T>
inline T* _allocate(ptrdiff_t size, T*){
set_new_handler(0) ; // ?
T* tmp = (T*) (::operator new((size_t) (size *sizeof(T)))); // :: operator
if(tmp == 0){
cout << "out of memory" <<endl;
exit(1);
}
return tmp;
}
template <class T>
inline void _deallocate (T* buffer){
::operator delete(buffer);
}
template <class T1,class T2>
inline void _construct(T1* p,const T2& value){
new(p) T1(value); // 存放 new 调用 构造函数 T1 .没理解 new(p)怎么玩的
}
template <class T>
inline void _destory(T* ptr){
ptr -> ~T();
}
template <class T>
class alloctor{
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;
// rebind allocator of type U
// allocator::rebind 是一个嵌套class template.class rebind<U>有唯一的一个成员other(是一个typedef,代表 allocate<U>)
template <class U>
struct rebind{
typedef allocator<U> other;
};
//配置空间,可以满足n个T对象 ,第二个参数是 一个提示。可以用这个参数来增加区域性,或者可以完全忽略
pointer allocate(size_type n,const void* hint=0){
return _allocate((difference_type)n, (pointer)0);
}
// 释放先前配置的空间
void deallocate (pointer p,size_type n){
_deallocate(p);
}
// 等价于 new((void*) p) T(x) // ???没有会等价
void construct(pointer p,const T& value){
_construct(p,value);
}
// 调用析构函数
void destory(pointer p){
_destory(p);
}
//返回对象的地址
pointer address(reference x){
return (pointer)&x;
}
//返回一个const对象的地址
const_pointer const_address(const_reference x){
return (const_pointer)&x;
}
//返回最大可成功分配的空间
size_type max_size() const{
return size_type(UINT_MAX/sizeof(T));
}
};
}
#endif // GRAVELALLOC_H_INCLUDED
#include "Gravelalloc.h"
#include <vector>
#include <iostream>
using namespace std;
int main(){
int a[5]={0,1,2,3,4};
vector<int,Gravel::alloctor<int> >v(a,a+5);
for(int i=0;i<v.size();++i){
cout<<v[i]<<' ';
}
cout<<endl;
return 0;
}