配置及构造
类
// 调用底层alloc
template <class T, class A = __default_alloc>
class simpleAlloc
{
public:
using value_type = T;
using pointer = T*;
using const_pointer = const T*;
using reference = T&;
using const_reference = const T&;
using size_type = size_t;
using difference_type = ptrdiff_t;
public :
// 分配空间的静态函数
static T* allocate();
static T* allocate(size_t n);
static void deallocate(T* ptr);
static void deallocate(T* ptr, size_t n);
static void construct(T* ptr);
static void construct(T* ptr, const T& value);
static void destory(T* ptr);
static void destory(T* first, T* last);
};
实现
// 静态方法
template <class T, class A>
T* simpleAlloc<T, A>::allocate()
{
return reinterpret_cast<T*>(A::allocate(sizeof(T)));
}
template <class T, class A>
T* simpleAlloc<T, A>::allocate(size_t n)
{
if (n == 0)
{
return 0;
}
return reinterpret_cast<T*>(A::allocate(sizeof(T) * n));
}
template <class T, class A>
void simpleAlloc<T, A>::deallocate(T* ptr)
{
A::deallocate(reinterpret_cast<void*>(ptr), sizeof(T));
}
template <class T, class A>
void simpleAlloc<T, A>::deallocate(T* ptr, size_t n)
{
if (n == 0)
{
return;
}
A::deallocate(reinterpret_cast<void*>(ptr), sizeof(T) * n);
}
template <class T, class A>
void simpleAlloc<T, A>::construct(T* ptr)
{
new (ptr) T();
}
template <class T, class A>
void simpleAlloc<T, A>::construct(T* ptr, const T& value)
{
new (ptr) T(value);
}
template <class T, class A>
void simpleAlloc<T, A>::destory(T* ptr)
{
ptr->~T();
}
template <class T, class A>
void simpleAlloc<T, A>::destory(T* first, T* last)
{
for (; first != last; first++)
{
first->~T();
}
}