Good day! I inherited the class allocator for using HeapAlloc as a source of allocated memory. The problem is the following: subsequent, starting from the second, memory allocations are completed with the exception of the type of access violatuion. Here is the 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); } 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); } 

    1 answer 1

    Without going into details ... when copying or assigning hHeap becomes invalid, because in the destructor HeapDestroy(hHeap); .

    With any destruction of any copy it turns out a lot of trouble.

    • you're right, thank you.) - Max