C++ custom template with unordered_map - c++

I am trying to create a custom template, and have such code:
template <typename T>
struct Allocator {
typedef T value_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
T *allocate(size_type n, const void *hint=0);
T *allocate_at_least(size_type n);
void deallocate(T *p, size_type n);
};
template <class T, class U>
bool operator==(const Allocator<T>&, const Allocator<U>&) {
return true;
}
int main() {
using T = long int;
std::unordered_map<
T,
T,
std::hash<T>,
std::equal_to<T>,
Allocator< std::pair<const T, T> >
> a;
}
It works with vector, but it fails somewhere inside the templates when I use unordered_map.
Can you help me to figure out what I am doing wrong?
Here is the error:
error: no matching constructor for initialization of 'std::__detail::_Hashtable_alloc<Allocator<std::__detail::_Hash_node<std::pair<const long, long>, false>>>::__buckets_alloc_type' (aka 'Allocator<std::__detail::_Hash_node_base *>')
And link to code: https://godbolt.org/z/zje3EGjb6
P.S. If I replace Allocator to std::allocator everything works fine.

It needs to have a default constructor and a constructor that is like a copy constructor but parametrized on a non-T type. The following compiles.
template <typename T>
struct Allocator {
typedef T value_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
T* allocate(size_type n, const void* hint = 0) {
return nullptr;
}
T* allocate_at_least(size_type n) {
return nullptr;
}
void deallocate(T* p, size_type n) {
}
Allocator() {} // <= this
template <class U>
Allocator(const Allocator<U>&) {} // <= and this
};
template <class T, class U>
bool operator==(const Allocator<T>&, const Allocator<U>&) {
return true;
}
int main() {
using T = long int;
std::unordered_map<
T,
T,
std::hash<T>,
std::equal_to<T>,
Allocator< std::pair<const T, T> >
> a;
}

Related

How I can write a monotonic allocator in C++?

I'm trying to write a very simple monotonic allocator that uses a fixed total memory size. Here is my code:
#include <map>
#include <array>
template <typename T, size_t SZ>
class monotonic_allocator
{
public:
using value_type = T;
monotonic_allocator() noexcept {}
[[nodiscard]]
value_type* allocate(std::size_t n)
{
size_t start = 0;
for (const auto& [alloc_start, alloc_size] : alloc_list_) {
if ((alloc_start - start) <= n) {
alloc_list_[start] = n;
return mem_.data() + start;
}
start = alloc_start + alloc_size;
}
throw std::bad_alloc{};
}
void deallocate(value_type* p, std::size_t n) noexcept
{
alloc_list_.erase(static_cast<size_t>(p - mem_.data()));
}
template <typename T1, size_t SZ1, typename T2, size_t SZ2>
friend bool operator==(monotonic_allocator<T1, SZ1> const& x, monotonic_allocator<T2, SZ2> const& y) noexcept;
private:
std::array<value_type, SZ> mem_;
std::map<size_t, size_t> alloc_list_{};
};
template <typename T1, size_t SZ1, typename T2, size_t SZ2>
bool operator==(monotonic_allocator<T1, SZ1> const& x, monotonic_allocator<T2, SZ2> const& y) noexcept
{
return SZ1 == SZ2 && x.mem_.data() == y.mem_.data();
}
template <typename T1, size_t SZ1, typename T2, size_t SZ2>
bool operator!=(monotonic_allocator<T1, SZ1> const& x, monotonic_allocator<T2, SZ2> const& y) noexcept
{
return !(x == y);
}
int main()
{
std::vector<int, monotonic_allocator<int, 4096>> vec = {1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,6};
}
But I get a strange error which says:
error: no type named 'type' in 'std::__allocator_traits_base::__rebind<monotonic_allocator<int, 4096>, int>'
Any idea how I can solve this problem? BTW, this code may have other problems too.
According to cppreference, rebind (which is part of the Allocator requirements) is only optional if your allocator is a template of the form <typename T, [possibly other type arguments]>. But your template is of the form <typename T, size_t N>, so it doesn't match (the size_t argument is a non-type argument).
So you have to add the rebind implementation yourself, like in the example in this question: How are allocator in C++ implemented?

How to align memory allocated for std::vector? [duplicate]

Is it possible to make std::vector of custom structs allocate aligned memory for further processing with SIMD instructions? If it is possible to do with Allocator, does anyone happen to have such an allocator he could share?
Edit: I removed the inheritance of std::allocator as suggested by GManNickG and made the alignment parameter a compile time thing.
I recently wrote this piece of code. It's not tested as much as I would like it so go on and report errors. :-)
enum class Alignment : size_t
{
Normal = sizeof(void*),
SSE = 16,
AVX = 32,
};
namespace detail {
void* allocate_aligned_memory(size_t align, size_t size);
void deallocate_aligned_memory(void* ptr) noexcept;
}
template <typename T, Alignment Align = Alignment::AVX>
class AlignedAllocator;
template <Alignment Align>
class AlignedAllocator<void, Align>
{
public:
typedef void* pointer;
typedef const void* const_pointer;
typedef void value_type;
template <class U> struct rebind { typedef AlignedAllocator<U, Align> other; };
};
template <typename T, Alignment Align>
class AlignedAllocator
{
public:
typedef T value_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef std::true_type propagate_on_container_move_assignment;
template <class U>
struct rebind { typedef AlignedAllocator<U, Align> other; };
public:
AlignedAllocator() noexcept
{}
template <class U>
AlignedAllocator(const AlignedAllocator<U, Align>&) noexcept
{}
size_type
max_size() const noexcept
{ return (size_type(~0) - size_type(Align)) / sizeof(T); }
pointer
address(reference x) const noexcept
{ return std::addressof(x); }
const_pointer
address(const_reference x) const noexcept
{ return std::addressof(x); }
pointer
allocate(size_type n, typename AlignedAllocator<void, Align>::const_pointer = 0)
{
const size_type alignment = static_cast<size_type>( Align );
void* ptr = detail::allocate_aligned_memory(alignment , n * sizeof(T));
if (ptr == nullptr) {
throw std::bad_alloc();
}
return reinterpret_cast<pointer>(ptr);
}
void
deallocate(pointer p, size_type) noexcept
{ return detail::deallocate_aligned_memory(p); }
template <class U, class ...Args>
void
construct(U* p, Args&&... args)
{ ::new(reinterpret_cast<void*>(p)) U(std::forward<Args>(args)...); }
void
destroy(pointer p)
{ p->~T(); }
};
template <typename T, Alignment Align>
class AlignedAllocator<const T, Align>
{
public:
typedef T value_type;
typedef const T* pointer;
typedef const T* const_pointer;
typedef const T& reference;
typedef const T& const_reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef std::true_type propagate_on_container_move_assignment;
template <class U>
struct rebind { typedef AlignedAllocator<U, Align> other; };
public:
AlignedAllocator() noexcept
{}
template <class U>
AlignedAllocator(const AlignedAllocator<U, Align>&) noexcept
{}
size_type
max_size() const noexcept
{ return (size_type(~0) - size_type(Align)) / sizeof(T); }
const_pointer
address(const_reference x) const noexcept
{ return std::addressof(x); }
pointer
allocate(size_type n, typename AlignedAllocator<void, Align>::const_pointer = 0)
{
const size_type alignment = static_cast<size_type>( Align );
void* ptr = detail::allocate_aligned_memory(alignment , n * sizeof(T));
if (ptr == nullptr) {
throw std::bad_alloc();
}
return reinterpret_cast<pointer>(ptr);
}
void
deallocate(pointer p, size_type) noexcept
{ return detail::deallocate_aligned_memory(p); }
template <class U, class ...Args>
void
construct(U* p, Args&&... args)
{ ::new(reinterpret_cast<void*>(p)) U(std::forward<Args>(args)...); }
void
destroy(pointer p)
{ p->~T(); }
};
template <typename T, Alignment TAlign, typename U, Alignment UAlign>
inline
bool
operator== (const AlignedAllocator<T,TAlign>&, const AlignedAllocator<U, UAlign>&) noexcept
{ return TAlign == UAlign; }
template <typename T, Alignment TAlign, typename U, Alignment UAlign>
inline
bool
operator!= (const AlignedAllocator<T,TAlign>&, const AlignedAllocator<U, UAlign>&) noexcept
{ return TAlign != UAlign; }
The implementation for the actual allocate calls is posix only but you can extent that easily.
void*
detail::allocate_aligned_memory(size_t align, size_t size)
{
assert(align >= sizeof(void*));
assert(nail::is_power_of_two(align));
if (size == 0) {
return nullptr;
}
void* ptr = nullptr;
int rc = posix_memalign(&ptr, align, size);
if (rc != 0) {
return nullptr;
}
return ptr;
}
void
detail::deallocate_aligned_memory(void *ptr) noexcept
{
return free(ptr);
}
Needs C++11, btw.
In the upcoming version 1.56, the Boost library will include Boost.Align. Among other memory alignment helpers it provides boost::alignment::aligned_allocator, which can be used a drop-in replacement for std::allocator and allows you to specify an alignment. See the documentation on https://boostorg.github.io/align/
Starting in C++17, just use std::vector<__m256i> or with any other aligned type. There's aligned version of operator new, it is used by std::allocator for aligned types (as well as by plain new-expression, so new __m256i[N] is also safe starting in C++17).
There's a comment by #MarcGlisse saying this, making this an answer to make it more visible.
Yes, it should be possible. If you put this question on google then you will get lots of sample code, below is some promising results:
https://bitbucket.org/marten/alignedallocator/wiki/Home
http://code.google.com/p/mastermind-strategy/source/browse/trunk/src/util/aligned_allocator.hpp?r=167
https://gist.github.com/1471329

Custom allocator only compiles in Release mode in VS 2015

I wrote a simple dummy allocator for vector<> so that I can use vector<> as a wrapper for stack arrays, like so:
#include <vector>
#include "stdio.h"
#include "stack_allocator.h"
using namespace std;
int main() {
int buffer[100];
vector<int, StackAllocator<int>> v((StackAllocator<int>(buffer, 100)));
v.push_back(2);
printf("%d", v[0]);
v.pop_back();
}
However, only in Debug Mode in VS2015, I get the following compiler error:
'std::StackAllocator<T2, std::allocator<T>>::StackAllocator(std::StackAllocator<T, std::allocator<T>> &&)':
cannot convert argument 1 from
'std::_Wrap_alloc<std::StackAllocator<int,std::allocator<T>>>'
to
'const std::allocator<T>&'
in "c:\program files (x86)\microsoft visual studio 14.0\vc\include\xmemory0" at line 952
Compilation and execution work as intended in Release mode, though.
Here is stack_allocator.h:
#pragma once
#include <functional>
namespace std {
template <typename T, typename Allocator = allocator<T>>
class StackAllocator {
public:
typedef typename allocator_traits<Allocator>::value_type value_type;
typedef typename allocator_traits<Allocator>::pointer pointer;
typedef typename allocator_traits<Allocator>::const_pointer const_pointer;
typedef typename allocator_traits<Allocator>::size_type size_type;
typedef typename allocator_traits<Allocator>::difference_type difference_type;
typedef typename allocator_traits<Allocator>::const_void_pointer const_void_pointer;
typedef typename Allocator::reference reference;
typedef typename Allocator::const_reference const_reference;
template<typename T2>
struct rebind {
typedef StackAllocator<T2> other;
};
private:
size_t m_size;
Allocator m_allocator;
pointer m_begin;
pointer m_end;
pointer m_stack_pointer;
bool pointer_to_internal_buffer(const_pointer p) const {
return (!(less<const_pointer>()(p, m_begin)) && (less<const_pointer>()(p, m_end)));
}
public:
StackAllocator(const Allocator& alloc = Allocator()) noexcept :
m_size(0),
m_allocator(alloc),
m_begin(nullptr),
m_end(nullptr),
m_stack_pointer(nullptr) {
}
StackAllocator(pointer buffer, size_t size, const Allocator& alloc = Allocator()) noexcept :
m_size(size),
m_allocator(alloc),
m_begin(buffer),
m_end(buffer + size),
m_stack_pointer(buffer) {
}
template <typename T2>
StackAllocator(const StackAllocator<T2, Allocator>& other) noexcept :
m_size(other.m_size),
m_allocator(other.m_allocator),
m_begin(other.m_begin),
m_end(other.m_end),
m_stack_pointer(other.m_stack_pointer) {
}
pointer allocate(size_type n, const_void_pointer hint = const_void_pointer()) {
if (n <= size_type(distance(m_stack_pointer, m_end))) {
pointer result = m_stack_pointer;
m_stack_pointer += n;
return result;
}
else
return m_allocator.allocate(n, hint);
}
void deallocate(pointer p, size_type n) {
if (pointer_to_internal_buffer(p))
m_stack_pointer -= n;
else
m_allocator.deallocate(p, n);
}
size_type capacity() const noexcept {
return m_size;
}
size_type max_size() const noexcept {
return m_size;
}
pointer address(reference x) const noexcept {
if (pointer_to_internal_buffer(addressof(x)))
return addressof(x);
else
return m_allocator.address(x);
}
const_pointer address(const_reference x) const noexcept {
if (pointer_to_internal_buffer(addressof(x)))
return addressof(x);
else
return m_allocator.address(x);
}
pointer buffer() const noexcept {
return m_begin;
}
template <typename T2, typename... Args>
void construct(T2* p, Args&&... args) {
m_allocator.construct(p, forward<Args>(args)...);
}
template <typename T2>
void destroy(T2* p) {
m_allocator.destroy(p);
}
template <typename T2>
bool operator==(const StackAllocator<T2, Allocator>& other) const noexcept {
return buffer() == other.buffer();
}
template <typename T2>
bool operator!=(const StackAllocator<T2, Allocator>& other) const noexcept {
return buffer() != other.buffer();
}
};
}
Anybody has a clue as to why this error is occurring? How do I solve it?
Your rebind is broken, it should be:
template<typename T2>
struct rebind {
using Alloc2
= typename allocator_traits<Allocator>::rebind_alloc<T2>;
using other = StackAllocator<T2, Alloc2>;
};
Otherwise rebinding always creates something using std::allocator<T2> not something related to the current Allocator argument.
e.g. if you instantiate StackAllocator<int, SomeAlloc<int> and then rebind it to long you get StackAllocator<long, std::allocator<long>> which is a completely different type.
I think the VC++ debug mode is creating some kind of wrapper allocator by rebinding yours, and it fails because of your broken rebind.
Also, these lines are a problem:
typedef typename Allocator::reference reference;
typedef typename Allocator::const_reference const_reference;
Types meeting the allocator requirements don't have to have reference and const_reference so by adding these typedefs you ensure your allocator can only work with a subset of allocators. If you think you need them, just define them the same way std::allocator does:
typedef value_type& reference;
typedef const value_type& const_reference;

Making std::vector allocate aligned memory

Is it possible to make std::vector of custom structs allocate aligned memory for further processing with SIMD instructions? If it is possible to do with Allocator, does anyone happen to have such an allocator he could share?
Edit: I removed the inheritance of std::allocator as suggested by GManNickG and made the alignment parameter a compile time thing.
I recently wrote this piece of code. It's not tested as much as I would like it so go on and report errors. :-)
enum class Alignment : size_t
{
Normal = sizeof(void*),
SSE = 16,
AVX = 32,
};
namespace detail {
void* allocate_aligned_memory(size_t align, size_t size);
void deallocate_aligned_memory(void* ptr) noexcept;
}
template <typename T, Alignment Align = Alignment::AVX>
class AlignedAllocator;
template <Alignment Align>
class AlignedAllocator<void, Align>
{
public:
typedef void* pointer;
typedef const void* const_pointer;
typedef void value_type;
template <class U> struct rebind { typedef AlignedAllocator<U, Align> other; };
};
template <typename T, Alignment Align>
class AlignedAllocator
{
public:
typedef T value_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef std::true_type propagate_on_container_move_assignment;
template <class U>
struct rebind { typedef AlignedAllocator<U, Align> other; };
public:
AlignedAllocator() noexcept
{}
template <class U>
AlignedAllocator(const AlignedAllocator<U, Align>&) noexcept
{}
size_type
max_size() const noexcept
{ return (size_type(~0) - size_type(Align)) / sizeof(T); }
pointer
address(reference x) const noexcept
{ return std::addressof(x); }
const_pointer
address(const_reference x) const noexcept
{ return std::addressof(x); }
pointer
allocate(size_type n, typename AlignedAllocator<void, Align>::const_pointer = 0)
{
const size_type alignment = static_cast<size_type>( Align );
void* ptr = detail::allocate_aligned_memory(alignment , n * sizeof(T));
if (ptr == nullptr) {
throw std::bad_alloc();
}
return reinterpret_cast<pointer>(ptr);
}
void
deallocate(pointer p, size_type) noexcept
{ return detail::deallocate_aligned_memory(p); }
template <class U, class ...Args>
void
construct(U* p, Args&&... args)
{ ::new(reinterpret_cast<void*>(p)) U(std::forward<Args>(args)...); }
void
destroy(pointer p)
{ p->~T(); }
};
template <typename T, Alignment Align>
class AlignedAllocator<const T, Align>
{
public:
typedef T value_type;
typedef const T* pointer;
typedef const T* const_pointer;
typedef const T& reference;
typedef const T& const_reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef std::true_type propagate_on_container_move_assignment;
template <class U>
struct rebind { typedef AlignedAllocator<U, Align> other; };
public:
AlignedAllocator() noexcept
{}
template <class U>
AlignedAllocator(const AlignedAllocator<U, Align>&) noexcept
{}
size_type
max_size() const noexcept
{ return (size_type(~0) - size_type(Align)) / sizeof(T); }
const_pointer
address(const_reference x) const noexcept
{ return std::addressof(x); }
pointer
allocate(size_type n, typename AlignedAllocator<void, Align>::const_pointer = 0)
{
const size_type alignment = static_cast<size_type>( Align );
void* ptr = detail::allocate_aligned_memory(alignment , n * sizeof(T));
if (ptr == nullptr) {
throw std::bad_alloc();
}
return reinterpret_cast<pointer>(ptr);
}
void
deallocate(pointer p, size_type) noexcept
{ return detail::deallocate_aligned_memory(p); }
template <class U, class ...Args>
void
construct(U* p, Args&&... args)
{ ::new(reinterpret_cast<void*>(p)) U(std::forward<Args>(args)...); }
void
destroy(pointer p)
{ p->~T(); }
};
template <typename T, Alignment TAlign, typename U, Alignment UAlign>
inline
bool
operator== (const AlignedAllocator<T,TAlign>&, const AlignedAllocator<U, UAlign>&) noexcept
{ return TAlign == UAlign; }
template <typename T, Alignment TAlign, typename U, Alignment UAlign>
inline
bool
operator!= (const AlignedAllocator<T,TAlign>&, const AlignedAllocator<U, UAlign>&) noexcept
{ return TAlign != UAlign; }
The implementation for the actual allocate calls is posix only but you can extent that easily.
void*
detail::allocate_aligned_memory(size_t align, size_t size)
{
assert(align >= sizeof(void*));
assert(nail::is_power_of_two(align));
if (size == 0) {
return nullptr;
}
void* ptr = nullptr;
int rc = posix_memalign(&ptr, align, size);
if (rc != 0) {
return nullptr;
}
return ptr;
}
void
detail::deallocate_aligned_memory(void *ptr) noexcept
{
return free(ptr);
}
Needs C++11, btw.
In the upcoming version 1.56, the Boost library will include Boost.Align. Among other memory alignment helpers it provides boost::alignment::aligned_allocator, which can be used a drop-in replacement for std::allocator and allows you to specify an alignment. See the documentation on https://boostorg.github.io/align/
Starting in C++17, just use std::vector<__m256i> or with any other aligned type. There's aligned version of operator new, it is used by std::allocator for aligned types (as well as by plain new-expression, so new __m256i[N] is also safe starting in C++17).
There's a comment by #MarcGlisse saying this, making this an answer to make it more visible.
Yes, it should be possible. If you put this question on google then you will get lots of sample code, below is some promising results:
https://bitbucket.org/marten/alignedallocator/wiki/Home
http://code.google.com/p/mastermind-strategy/source/browse/trunk/src/util/aligned_allocator.hpp?r=167
https://gist.github.com/1471329

Why doesn't this C++ STL allocator allocate?

I'm trying to write a custom STL allocator that is derived from std::allocator, but somehow all calls to allocate() go to the base class. I have narrowed it down to this code:
template <typename T> class a : public std::allocator<T> {
public:
T* allocate(size_t n, const void* hint = 0) const {
cout << "yo!";
return 0;
}
};
int main()
{
vector<int, a<int>> v(1000, 42);
return 0;
}
I expect "Yo!" to get printed, followed by some horrible error because I don't actually allocate anything. Instead, the program runs fine and prints nothing. What am I doing wrong?
I get the same results in gcc and VS2008.
You will need to provide a rebind member template and the other stuff that is listed in the allocator requirements in the C++ Standard. For example, you need a template copy constructor which accepts not only allocator<T> but also allocator<U>. For example, one code might do, which a std::list for example is likely to do
template<typename Allocator>
void alloc1chunk(Allocator const& alloc) {
typename Allocator::template rebind<
wrapper<typename Allocator::value_type>
>::other ot(alloc);
// ...
}
The code will fail if there either exist no correct rebind template, or there exist no corresponding copy constructor. You will get nowhere useful with guessing what the requirements are. Sooner or later you will have to do with code that relies on one part of those allocator requirements, and the code will fail because your allocator violates them. I recommend you take a look at them in some working draft your your copy of the Standard in 20.1.5.
In this case, the problem is that I didn't override the rebind member of the allocator. This version works (in VS2008):
template <typename T> class a : public std::allocator<T> {
public:
T* allocate(size_t n, const void* hint = 0) const {
cout << "yo!";
return 0;
}
template <typename U> struct rebind
{
typedef a<U> other;
};
};
int main() {
vector<int, a<int>> v(1000, 42);
return 0;
}
I found this by debugging through the STL headers.
Whether this works or not will be completely dependent on the STL implementation though, so I think that ultimately, Klaim is right in that this shouldn't be done this way.
I have two templates for creating customized allocators; the first works automagically if it is used on a custom type:
template<>
class std::allocator<MY_TYPE>
{
public:
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef MY_TYPE* pointer;
typedef const MY_TYPE* const_pointer;
typedef MY_TYPE& reference;
typedef const MY_TYPE& const_reference;
typedef MY_TYPE value_type;
template <class U>
struct rebind
{
typedef std::allocator<U> other;
};
pointer allocate(size_type n, std::allocator<void>::const_pointer hint = 0)
{
return reinterpret_cast<pointer>(ALLOC_FUNC(n * sizeof(T)));
}
void construct(pointer p, const_reference val)
{
::new(p) T(val);
}
void destroy(pointer p)
{
p->~T();
}
void deallocate(pointer p, size_type n)
{
FREE_FUNC(p);
}
size_type max_size() const throw()
{
// return ~size_type(0); -- Error, fixed according to Constantin's comment
return std::numeric_limits<size_t>::max()/sizeof(MY_TYPE);
}
};
The second is used when we want to have our own allocator for a predefined type with a standard allocator, for instance char, wchar_t, std::string, etc.:
namespace MY_NAMESPACE
{
template <class T> class allocator;
// specialize for void:
template <>
class allocator<void>
{
public:
typedef void* pointer;
typedef const void* const_pointer;
// reference to void members are impossible.
typedef void value_type;
template <class U>
struct rebind
{
typedef allocator<U> other;
};
};
template <class T>
class allocator
{
public:
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
template <class U>
struct rebind
{
typedef allocator<U> other;
};
allocator() throw()
{
}
template <class U>
allocator(const allocator<U>& u) throw()
{
}
~allocator() throw()
{
}
pointer address(reference r) const
{
return &r;
}
const_pointer address(const_reference r) const
{
return &r;
}
size_type max_size() const throw()
{
// return ~size_type(0); -- Error, fixed according to Constantin's comment
return std::numeric_limits<size_t>::max()/sizeof(T);
}
pointer allocate(size_type n, allocator<void>::const_pointer hint = 0)
{
return reinterpret_cast<pointer>(ALLOC_FUNC(n * sizeof(T)));
}
void deallocate(pointer p, size_type n)
{
FREE_FUNC(p);
}
void construct(pointer p, const_reference val)
{
::new(p) T(val);
}
void destroy(pointer p)
{
p->~T();
}
};
template <class T1, class T2>
inline
bool operator==(const allocator<T1>& a1, const allocator<T2>& a2) throw()
{
return true;
}
template <class T1, class T2>
inline
bool operator!=(const allocator<T1>& a1, const allocator<T2>& a2) throw()
{
return false;
}
}
The first template above, for your own defined type, does not require any further handling but is used automatically by the standard container classes. The second template requires further work when used on a standard type. For std::string, for example, one have to use the following construct when declaring variables of that type (it is simplest with a typedef):
std::basic_string<char>, std::char_traits<char>, MY_NAMESPACE::allocator<char> >
The following code prints "yo" as expected - what you were seeing was our old friend "undefined behaviour".
#include <iostream>
#include <vector>
using namespace std;
template <typename T> class a : public std::allocator<T> {
public:
T* allocate(size_t n, const void* hint = 0) const {
cout << "yo!";
return new T[10000];
}
};
int main()
{
vector<int, a<int> > v(1000, 42);
return 0;
}
Edit: I just checked out the C++ Standard regarding the default allocator. There is no prohibition on inheriting from it. In fact, as far as I'm aware, there is no such prohibition in any part of the Standard.