Skip to content

Instantly share code, notes, and snippets.

@ericherman
Created February 23, 2019 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericherman/67e7b71981a059dd8c7a2ebaa1c6c36a to your computer and use it in GitHub Desktop.
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
#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