Skip to content

Instantly share code, notes, and snippets.

@jacquelinekay
Last active April 13, 2023 18:10
Show Gist options
  • Save jacquelinekay/0cee73d1d2d78d8edd31 to your computer and use it in GitHub Desktop.
Save jacquelinekay/0cee73d1d2d78d8edd31 to your computer and use it in GitHub Desktop.
allocator_traits rebind_alloc example
#include <memory>
#include <string>
// Example allocator, doesn't do anything but implements std::allocator_traits
template<typename T>
struct null_allocator {
using value_type = T;
null_allocator() {}
template<typename U>
null_allocator(const null_allocator<U>&) {}
T* allocate(size_t size) {
(void) size;
return NULL;
}
void deallocate(T* ptr, size_t size) {
(void) ptr;
(void) size;
}
};
template<typename T, typename U>
constexpr bool operator== (const null_allocator<T>&, const null_allocator<U>&) noexcept {
return true;
}
template<typename T, typename U>
constexpr bool operator!= (const null_allocator<T>&, const null_allocator<U>&) noexcept {
return false;
}
template<typename T>
using RebindAlloc = typename std::allocator_traits<null_allocator<void>>::template rebind_alloc<T>;
using MyString = std::basic_string<char, std::char_traits<char>, RebindAlloc<char>>;
int main(int /*argc*/, char ** /*argv*/)
{
// check that null_allocator follows allocator_traits
test::null_allocator<void> alloc;
void * ptr = std::allocator_traits<null_allocator<void>>::allocate(alloc, 1);
MyString string;
}
@leukios
Copy link

leukios commented Mar 21, 2016

Can you tell me how to compile the example? It reported error when I compiled it in gcc 4.9.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment