Last active
April 13, 2023 18:10
-
-
Save jacquelinekay/0cee73d1d2d78d8edd31 to your computer and use it in GitHub Desktop.
allocator_traits rebind_alloc example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you tell me how to compile the example? It reported error when I compiled it in gcc 4.9.