Why do standard containers require allocator_type::value_type to be the element type?
Asked Answered
M

1

5

Related: Deprecation of std::allocator<void>.

The following description about template parameter Allocator is found for both std::vector and std::list (emphasis mine):

An allocator that is used to acquire/release memory and to construct/destroy the elements in that memory. The type must meet the requirements of Allocator. The behavior is undefined if Allocator::value_type is not the same as T.

The last sentence does not make sense to me. If a specific value_type is required, couldn't it just do an allocator rebind?

Morton answered 9/5, 2018 at 3:53 Comment(4)
I actually couldn't find this requirement in the standard. I am either missing it, or cpp reference here is not correct.Lipoma
@Lipoma This is given indirectly in the "Allocator-aware container requirements" table in [container.requirements.general], assertion/note for the allocator_type expression.Burdock
@1201ProgramAlarm, oh, general container requirements! Thanks.Lipoma
Huh, one more crazy thing to add to the list about allocators I suppose. This is particularly weird since std::list is almost certainly rebinding to an internal node typeBankhead
H
1

The reason is mostly historical—rebinding was more complicated before C++11 added allocator_traits. The Networking TS defines a “proto-allocator” concept ([async.reqmts.proto.allocator]) where rebinding is always applied before any use, so it seems likely that the requirement will be relaxed someday.

Histogen answered 10/5, 2018 at 0:26 Comment(1)
I think the reason is even more historical. When STL was written, C++ probably didn't have template template class parameters. Otherwise, we could have the much more logical, std::vector<T, std::allocator> or std::list<T, std::allocator>, and it would be the class's responsibility to generate the type std::allocator<T> (or std::allocator<TNode>).Sheers

© 2022 - 2024 — McMap. All rights reserved.