问题描述:

I written allocator with allocation from heap. I have some trouble with memory allocate. First allocation was successfull, but the next one crashed by access violation. I can't understand where is my problem. There are code:

#define NOMINMAX

#include <Windows.h>

#include <memory>

#include <iostream>

#include <limits>

#include <sstream>

template<class T>

class HeapAllocator

{

private :

HANDLE hHeap;

size_t size;

public:

using value_type = T;

using Traits = std::allocator_traits<HeapAllocator<T>>;

using size_type = std::size_t;

using difference_type = std::ptrdiff_t;

using pointer = T*;

using const_pointer = const T *;

using reference = T &;

using const_reference = const T &;

T * allocate(std::size_t n);

pointer address(reference value) const { return &value; }

const_pointer address(const_reference value) const { return &value; }

void deallocate(T * p, std::size_t n);

size_type max_size() const { return std::numeric_limits<size_type>::max() / sizeof(T); }

template<class U, class... Args>

void construct(U* p, Args&&... args) { std::allocator<T>().construct(p, std::forward<Args>(args)...); }

template<class U>

void destroy(U* p) { std::allocator<T>().destroy(p); }

HeapAllocator();

~HeapAllocator();

template<class U>

struct rebind

{

using other = HeapAllocator<U>;

};

template<class U>

HeapAllocator(const HeapAllocator<U> & other) {}

};

template<class T>

HeapAllocator<T>::HeapAllocator()

{

hHeap = HeapCreate(HEAP_CREATE_ENABLE_EXECUTE|

HEAP_NO_SERIALIZE,

1024, 0);

size = sizeof(T);

}

template<class T>

HeapAllocator<T>::~HeapAllocator()

{

HeapDestroy(hHeap);

}

template<class T1, class T2>

bool operator==(const HeapAllocator<T1> &, const HeapAllocator<T2> &) throw()

{

return true;

}

template <class T1, class T2>

bool operator!=(const HeapAllocator<T1>&,

const HeapAllocator<T2>&) throw() {

return false;

}

template<class T>

T * HeapAllocator<T>::allocate(std::size_t n)

{

void *p = nullptr;

p = HeapAlloc(hHeap, 0, sizeof(T) * n);

if (p == nullptr)

std::cerr << GetLastError() << '\n';

return reinterpret_cast<T *>(p);

}

template<class T>

void HeapAllocator<T>::deallocate(T *p, size_t n)

{

HeapFree(hHeap, 0, p);

}

相关阅读:
Top