Created
February 23, 2019 19:19
-
-
Save ericherman/67e7b71981a059dd8c7a2ebaa1c6c36a to your computer and use it in GitHub Desktop.
demonstrates a problem I ran into with custom allocators which require a constructor argument and generic containers
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 <limits> | |
#include <list> | |
template <typename T> class FooAllocator { | |
char my_c; | |
public: | |
typedef T value_type; | |
typedef value_type *pointer; | |
typedef const value_type *const_pointer; | |
typedef value_type &reference; | |
typedef const value_type &const_reference; | |
typedef std::size_t size_type; | |
typedef std::ptrdiff_t difference_type; | |
template <typename U> struct rebind { typedef FooAllocator<U> other; }; | |
inline explicit FooAllocator(char c) { my_c = c; } | |
inline ~FooAllocator() {} | |
inline explicit FooAllocator(FooAllocator const &) {} | |
template <typename U> | |
inline explicit FooAllocator(FooAllocator<U> const &) {} | |
inline pointer address(reference r) { return &r; } | |
inline const_pointer address(const_reference r) { return &r; } | |
inline pointer | |
allocate(size_type cnt, | |
typename std::allocator<void>::const_pointer = 0) { | |
return reinterpret_cast<pointer>( | |
::operator new(cnt * sizeof(T))); | |
} | |
inline void deallocate(pointer p, size_type) { ::operator delete(p); } | |
inline size_type max_size() const { | |
return std::numeric_limits<size_type>::max() / sizeof(T); | |
} | |
inline void construct(pointer p, const T &t) { new (p) T(t); } | |
inline void destroy(pointer p) { p->~T(); } | |
inline bool operator==(FooAllocator const &) { return true; } | |
inline bool operator!=(FooAllocator const &a) { return !operator==(a); } | |
}; // end of class FooAllocator | |
typedef std::list<int, FooAllocator<int>> Intlist; | |
int main(void) { | |
FooAllocator<int> foo('a'); | |
Intlist l(foo); | |
l.push_back(3); | |
l.push_back(1); | |
l.push_back(4); | |
// uncomment the next line to break (tested with g++ 8.2): | |
// l.sort(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment