What is the purpose of requiring an STL allocator instance constructor
The STL places some restrictions on allocators, which include the following:>
a1 == a2 returns true only if storage allocated by allocator a1 can be freed via a2. Establishes reflexive, symmetric and transitive relationships. Throws no exceptions.
A a (b) Creates a such that B (a) == b and A (b) == a. Doesn't throw exceptions. (Note: this means that all reparse-related allocators support each other's resources, such as memory pools).
At first, I misinterpreted requirement 2 as: " A a (b) Creates a such that a == b." Which, in my opinion, might be a common mistake, but given the correct interpretation of 2, in what use cases would this be really useful? I assume most of the time the body of the copy constructor will be empty. Can it, for example, be used to copy a file pointer to be used for allocations?
source to share
As noted in the comment, allocators can bounce to different types.
More often than not, allocator instances for different types have (implicit) conversions, so you can go Alloc<void>
where expected Alloc<int>
and vice versa.
So when you do
MyAlloc<int> ia;
MyAlloc<double> da;
bool equivalent = (ia == da);
What you really do is
bool equivalent = operator==(ia, da);
which will implicitly convert da
to MyAlloc<int>
if no heterogeneous overload exists operator==
.
This requirement requires an implementation to explicitly convert the rhs allocator to the same allocator type. it
- avoids accidentally hitting heterogeneous overloads
operator==
and - has the advantage of still working even if the conversion constructor is checked
explicit
.
bool equivalent = operator==(ia, MyAlloc<int>(da)); // or:
bool equivalent = operator==(da, MyAlloc<double>(ia)); // or:
At the same time, this allows different valve types to still compare non-equivalent ones.
ยน Check if this is indicated as a requirement
source to share