添加Allocator来包装Alloc

This commit is contained in:
邹晓航
2014-09-18 14:42:09 +08:00
parent 90699d642e
commit c5ed377753
5 changed files with 77 additions and 5 deletions

View File

@@ -6,7 +6,8 @@
namespace TinySTL{
/*
**<2A>ռ<EFBFBD><D5BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
**<2A>ռ<EFBFBD><D5BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ֽ<EFBFBD><EFBFBD><EFBFBD>Ϊ<EFBFBD><EFBFBD>λ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>
**<2A>ڲ<EFBFBD>ʹ<EFBFBD><CAB9>
*/
class alloc{
private:

66
TinySTL/Allocator.h Normal file
View File

@@ -0,0 +1,66 @@
#ifndef _ALLOCATOR_H_
#define _ALLOCATOR_H_
#include "Alloc.h"
#include "Construct.h"
#include <new>
namespace TinySTL{
/*
**<2A>ռ<EFBFBD><D5BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ա<EFBFBD><D4B1><EFBFBD><EFBFBD><EFBFBD>ĿΪ<C4BF><CEAA>λ<EFBFBD><CEBB><EFBFBD><EFBFBD>
*/
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

View File

@@ -80,6 +80,7 @@
</ItemGroup>
<ItemGroup>
<ClInclude Include="Alloc.h" />
<ClInclude Include="Allocator.h" />
<ClInclude Include="Construct.h" />
<ClInclude Include="TypeTraits.h" />
</ItemGroup>

View File

@@ -29,5 +29,8 @@
<ClInclude Include="Alloc.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="Allocator.h">
<Filter>头文件</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@@ -1,16 +1,17 @@
#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;