提交 c5ed3777 编写于 作者: 邹晓航

添加Allocator来包装Alloc

上级 90699d64
......@@ -6,7 +6,8 @@
namespace TinySTL{
/*
**空间配置器
**空间配置器,以字节数为单位分配
**内部使用
*/
class alloc{
private:
......
#ifndef _ALLOCATOR_H_
#define _ALLOCATOR_H_
#include "Alloc.h"
#include "Construct.h"
#include <new>
namespace TinySTL{
/*
**空间配置器,以变量数目为单位分配
*/
template<class T>
class allocator{
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;
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 destroy(T *ptr);
};
template<class T>
T *allocator<T>::allocate(){
return static_cast<T *>(alloc::allocate(sizeof(T)));
}
template<class T>
T *allocator<T>::allocate(size_t n){
return static_cast<T *>(alloc::allocate(sizeof(T) * n));
}
template<class T>
void allocator<T>::deallocate(T *ptr){
alloc::deallocate(static_cast<void *>(ptr), sizeof(T));
}
template<class T>
void allocator<T>::deallocate(T *ptr, size_t n){
alloc::deallocate(static_cast<void *>(ptr), sizeof(T)* n);
}
template<class T>
void allocator<T>::construct(T *ptr){
new(ptr)T();
}
template<class T>
void allocator<T>::construct(T *ptr, const T& value){
new(ptr)T(value);
}
template<class T>
void allocator<T>::destroy(T *ptr){
ptr->~T();
}
}
#endif
\ No newline at end of file
......@@ -80,6 +80,7 @@
</ItemGroup>
<ItemGroup>
<ClInclude Include="Alloc.h" />
<ClInclude Include="Allocator.h" />
<ClInclude Include="Construct.h" />
<ClInclude Include="TypeTraits.h" />
</ItemGroup>
......
......@@ -29,5 +29,8 @@
<ClInclude Include="Alloc.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="Allocator.h">
<Filter>头文件</Filter>
</ClInclude>
</ItemGroup>
</Project>
\ No newline at end of file
#include <iostream>
#include <memory>
#include "Alloc.h"
#include "Allocator.h"
#include "Construct.h"
using namespace std;
int main(){
for (int i = 1; i != 100000; ++i){
TinySTL::alloc::allocate(i % 128 * sizeof(int));
//std::allocator<int> alloc; alloc.allocate(i % 128);
//malloc(i % 128 * sizeof(int));
auto p = TinySTL::allocator<int>::allocate();
TinySTL::allocator<int>::construct(p, i);
TinySTL::allocator<int>::destroy(p);
TinySTL::allocator<int>::deallocate(p);
}
system("pause");
return 0;
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册