在 C++ 中,自定義分配器(allocator)允許您控制內(nèi)存分配和釋放的方式。要自定義分配器,您需要繼承 std::allocator
類并重寫其成員函數(shù)。以下是一個(gè)簡(jiǎn)單的自定義分配器示例:
#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;
}
在這個(gè)示例中,我們創(chuàng)建了一個(gè)名為 MyAllocator
的自定義分配器,它繼承自 std::allocator<T>
。我們重寫了 allocate
、deallocate
、construct
和 destroy
成員函數(shù),以便在分配和釋放內(nèi)存時(shí)執(zhí)行一些自定義操作。在 main
函數(shù)中,我們使用 MyAllocator
創(chuàng)建了一個(gè) std::vector<int>
實(shí)例,并向其中添加了一些整數(shù)。當(dāng)執(zhí)行這些操作時(shí),您將看到自定義分配器的輸出。