As far as I can tell, the requirements on an allocator to be used with STL
containers are laid out in Table 28 of section 17.6.3.5 of the C++11 standard.
I'm a bit confused about the interaction between some of these requirements.
Given a type X
that is an allocator for type T
, a type Y
that is "the
corresponding allocator class" for type U
, instances a
, a1
, and a2
of
X
, and an instance b
of Y
, the table says:
The expression a1 == a2
evaluates to true
only if storage allocated
from a1
can be deallocated by a2
, and vice versa.
The expression X a1(a);
is well-formed, doesn't exit via an exception,
and afterward a1 == a
is true.
The expression X a(b)
is well-formed, doesn't exit via an exception, and
afterward a == b
.
I read this as saying that all allocators must be copy-constructible in such a
way that the copies are interchangeable with the originals. Worse, the same
true across type boundaries. This seems to be a pretty onerous requirement; as
far as I can tell, it makes impossible a large number of types of allocators.
For example, say I had a freelist class that I wanted to use in my allocator,
in order to cache freed objects. Unless I'm missing something, I couldn't
include an instance of that class in the allocator, because the sizes or
alignments of T
and U
might differ and therefore the freelist entries are
not compatible.
My questions:
Are my interpretations above correct?
I've read in a few places that C++11 improved support for "stateful
allocators". How is that the case, given these restrictions?
Do you have any suggestions for how to do the sort of thing I'm trying to
do? That is, how do I include allocated-type-specific state in my allocator?
In general, the language around allocators seems sloppy. (For example, the
prologue to Table 28 says to assume that a
is of type X&
, but some of the
expressions redefine a
.) Also, at least GCC's support is non-conformant.
What accounts for this weirdness around allocators? Is it just an infrequently
used feature?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…