Как реализовать простой распределитель для использования с контейнерами STL?C++

Программы на C++. Форум разработчиков
Anonymous
Как реализовать простой распределитель для использования с контейнерами STL?

Сообщение Anonymous »

У меня есть распределитель, который отлично работает с std::vector, но имеет ошибки компиляции с std::basic_string. Вот мой код:

Код: Выделить всё

#include 
#include 
#include 

template 
struct MyAllocator {
typedef T value_type;
typedef T* pointer;
typedef T* const const_pointer;
typedef T& reference;
typedef T const& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
MyAllocator() = default;

template 
MyAllocator(const MyAllocator&) {}

template 
struct rebind {
typedef MyAllocator other;
};

pointer allocate(size_t n) {
void* chunk = ::operator new(n * sizeof(value_type));
if (chunk == nullptr) {
throw std::bad_alloc();
}
return static_cast
(chunk);
}

void deallocate(pointer p, size_t n) {
::operator delete(p);
}
template 
void construct(void* p, Args&&...  args) {
::new(p) T(std::forward(args)...);
}

void destroy(pointer p) {
p->~T();
}
bool operator==(const MyAllocator&) const {
return true;
}
bool operator!=(const MyAllocator&) const {
return false;
}
};

typedef std::basic_string my_string;

int main() {
#if defined(V_TEST)
std::vector v_test = {1, 2, 3, 4, 5, 6};
std::cout 

Подробнее здесь: [url]https://stackoverflow.com/questions/78434496/how-to-implement-simple-allocator-for-use-with-stl-containers[/url]

Вернуться в «C++»