在 C++ 中,自定义分配器(allocator)允许您控制内存分配和释放的方式。要自定义分配器,您需要继承 std::allocator
类并重写其成员函数。以下是一个简单的自定义分配器示例:
#include <iostream>
#include <memory>
#include <vector>
template <typename T>
class MyAllocator : public std::allocator<T> {
public:
using value_type = T;
using pointer = T*;
using const_pointer = const T*;
using reference = T&;
using const_reference = const T&;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
template <typename U>
struct rebind {
typedef MyAllocator<U> other;
};
MyAllocator() noexcept {}
template <typename U>
MyAllocator(const MyAllocator<U>&) noexcept {}
pointer allocate(size_type n, const void* hint = 0) {
std::cout << "MyAllocator::allocate("<< n << ")\n";
return static_cast<pointer>(std::allocator<T>::allocate(n, hint));
}
void deallocate(pointer p, size_type n) noexcept {
std::cout << "MyAllocator::deallocate("<< p << ", "<< n << ")\n";
std::allocator<T>::deallocate(p, n);
}
size_type max_size() const noexcept {
return std::numeric_limits<size_type>::max() / sizeof(T);
}
template <typename U, typename... Args>
void construct(U* p, Args&&... args) {
std::cout << "MyAllocator::construct("<< p << ", " << args... << ")\n";
std::allocator<T>::construct(p, std::forward<Args>(args)...);
}
template <typename U>
void destroy(U* p) {
std::cout << "MyAllocator::destroy("<< p << ")\n";
std::allocator<T>::destroy(p);
}
};
int main() {
std::vector<int, MyAllocator<int>> vec;
vec.reserve(10);
for (int i = 0; i < 10; ++i) {
vec.emplace_back(i);
}
return 0;
}
在这个示例中,我们创建了一个名为 MyAllocator
的自定义分配器,它继承自 std::allocator<T>
。我们重写了 allocate
、deallocate
、construct
和 destroy
成员函数,以便在分配和释放内存时执行一些自定义操作。在 main
函数中,我们使用 MyAllocator
创建了一个 std::vector<int>
实例,并向其中添加了一些整数。当执行这些操作时,您将看到自定义分配器的输出。