#ifndef _DEF_ALLOC_ #define _DEF_ALLOC_ 1 #include #include #include #include namespace nanxing { template constexpr inline T* _allocate(ptrdiff_t size, T*) noexcept //这个是STL标准的要求,第二个传入的T*没啥用(在实际调用的时候会传入一个空指针) { T* temp; try { temp = (T*)(::operator new((size_t)(size * (sizeof(T))))); } catch(...) { return nullptr; //如果出现失败会直接返回nullptr } return temp; } //template // inline void _construct(T1* p, const T2& x) // { // ::new(p) T1(x); //在p指向空间上调用构造函数 // } template inline void _construct(_Up* __p, _Args&&... __args) noexcept(std::is_nothrow_constructible<_Up, _Args...>::value) { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); } template constexpr inline void _deallocate(T* buffer) { ::operator delete(buffer); //释放空间(注意和delete的区别) } template constexpr inline void _destory(T* ptr) { ptr->~T(); //调用析构函数 } template class allocator { public: using value_type = T; using pointer = T*; using const_pointer = const T*; using reference = T&; using size_type = size_t; using difference_type = ptrdiff_t; using const_reference = const T&; constexpr allocator() noexcept { //std::cout<<"hello"< struct rebind { using other = allocator; }; constexpr pointer allocate(size_type n, const void* hint = 0) //注意这个函数是会抛出一个std::bad_alloc异常 { return _allocate((difference_type)n, (pointer)0); } template void construct(pointer __p, _Args&&... __args) noexcept { _construct(__p,std::forward<_Args>(__args)...); //::new((void *)__p) _Up(std::forward<_Args>(__args)...); } // template // void construct(pointer p,const T2& data )noexcept //唯一参数版本 // { // _construct(p,data); // } constexpr void deallocate(pointer p, size_type n=0) { _deallocate(p); } constexpr void destory(pointer p) { _destory(p); } constexpr pointer address(reference x) { return (pointer)&x; } constexpr const_pointer address(const_reference x) { return (const_pointer)&x; } constexpr size_type max_size()const { return size_type(UINT_MAX / sizeof(T)); } }; } #endif