直接上代码
template<typename T>
class Allocator
{
public:
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
public:
Allocator()
{
// std::cout << "Allocator()" << std::endl;
}
Allocator(const Allocator& alloc)
{
// std::cout << "Allocator(const Allocator&)" << std::endl;
}
~Allocator()
{
// std::cout << "~Allocator()" << std::endl;
}
// Allocator& operator=(const Allocator&) = default;
template <typename _Tp1>
struct rebind
{
typedef Allocator<_Tp1> other;
};
pointer address(reference __x) const noexcept
{
return std::__addressof(__x);
}
const_pointer address(const_reference __x) const noexcept
{
return std::__addressof(__x);
}
pointer allocate(size_type __n, const void* = static_cast<const void*>(0))
{
if (__n > max_size())
std::__throw_bad_alloc();
// std::cout << "allocate(" << __n << ")" << std::endl;
return static_cast<pointer>(::operator new(__n * sizeof(value_type)));
// return static_cast<pointer>(gMem);
}
void deallocate(pointer __p, size_type)
{
::operator delete(__p);
}
size_type max_size() const
{
// std::cout << "max_size():" << __PTRDIFF_MAX__ << std::endl;
return size_t(__PTRDIFF_MAX__) / sizeof(value_type);
}
template <typename _Up, typename... _Args>
void construct(_Up* __p, _Args&&... __args) noexcept(std::is_nothrow_constructible<_Up, _Args...>::value)
{
// std::cout << "construct(" << __p << ")" << typeid(_Up).name() << std::endl;
::new ((void*)__p) _Up(std::forward<_Args>(__args)...);
}
template <typename _Up>
void destroy(_Up* __p) noexcept(std::is_nothrow_destructible<_Up>::value)
{
// std::cout << "destroy(" << __p << ")" << typeid(_Up).name() << std::endl;
__p->~_Up();
}
template <typename _Up>
friend bool operator==(const new_allocator&, const new_allocator<_Up>&) noexcept
{
return true;
}
template <typename _Up>
friend bool operator!=(const new_allocator&, const new_allocator<_Up>&) noexcept
{
return false;
}
};
在使用的时候需要注意
1.修改allocate和deallocate函数,替换为自己的创建和回收实现。
2.在针对basic_string使用要注意,basic_string如果字符串小于16字节不会使用分配器,而是使用对象内部预定义的16字节内存空间。