#pragma once
#ifndef _XMEMORYS_H_
#define _XMEMORYS_H_
using namespace std;
#include<iostream>
#include<xutility>
#include<memory>
#include<xmemory>
#include<new>
template<class _Ty>
inline _Ty* _allocate(size_t size, _Ty*)
{
// 在尚未用set_new_handler设置处理函数,或者设置的处理函数为空时,
//将调用默认的处理函数,该函数在内存分配失败时抛出bad_alloc异常。
try
{
set_new_handler(0);
_Ty* tmp = static_cast<_Ty*>(::operator new(size * sizeof(_Ty)));
if (tmp == 0)
{
cerr << "out of memory" << endl;
exit(0);
}
return tmp;
}
catch (...)
{
}
}
template<class _Ty>
inline void _deallocate(_Ty* buffer)
{
try
{
if (buffer)
{
::operator delete(buffer);
}
}
catch (...)
{
}
}
template<class T>
class allocator
{
public:
using pointer = T*;
using size_type = size_t;
template<class U>
struct rebinds
{
typedef allocators<U> other;
};
//申请内存空间,返回指针
pointer allocate(size_type n, const void* hint = 0)
{
return _allocate(n, (pointer)0);
}
//释放内存空间
void deallocate(pointer p, size_type n)
{
_deallocate(p);
}
//在未初始化的内存上构造单个对象
void _construct(pointer p, const T& value)
{
construct_at(p, value); //标准库函数
}
//析构单个对象,没有释放内存
void _destory_at(pointer p)
{
destroy_at(p); //标准库函数
}
//析构n个对象,没有释放内存
void _destory_n(pointer p,size_t n)
{
destroy(p, p + n); //标准库函数
}
//返回能够存储对象的最大数量
size_type _max_size()const
{
return size_type(UINT_MAX / sizeof(T));
}
//对未初始化区域调用拷贝构造函数初始化
void _uninitialized_copy(pointer first, pointer last, pointer dest)
{
uninitialized_copy(first, last, dest); //标准库函数
}
//对未初始化区域调用拷贝构造函数初始化
void _uninitialized_copy_n(pointer first, size_t n, pointer dest)
{
uninitialized_copy_n(first, n, dest); //标准库函数
}
//对未初始化区域调用默认构造函数初始化
void _uninitialized_default_construct(pointer first, pointer last)
{
uninitialized_default_construct(first, last); //标准库函数
}
//对未初始化区域调用默认构造函数初始化
void _uninitialized_default_construct_n(pointer first, size_t n)
{
uninitialized_default_construct_n(first, n); //标准库函数
}
//对未初始化区域调用拷贝构造函数初始化
void _uninitialized_fill(pointer first, pointer last, const T& val)
{
uninitialized_fill(first, last, val); //标准库函数
}
//对未初始化区域调用拷贝构造函数初始化
void _uninitialized_fill_n(pointer first, size_t n, const T& val)
{
uninitialized_fill_n(first, n, val); //标准库函数
}
allocator(){}
allocator(const allocator& rhs) {}
allocator& operator=(const allocator&rhs) = default;
~allocator()noexcept{}
};
#endif
自己写的一个空间适配器allocator,使用C++库的接口
发布于 2022-12-03 304 次阅读
Comments NOTHING