c++stlnested-types

Why do they use pointer, void_pointer and other typedef inside allocator and vector classes of STL?


Looking at the https://en.cppreference.com/w/cpp/memory/allocator

value_type is typedef(or alias) of T,

pointer is typedef(or alias) of T*,

void_pointer is typedef(or alias) of void*,

Why do we need this from the point of view of STL developers? Isn't T* always a pointer? Isn't void* always a pointer to void? Give me some explanation or links, please. I don't really understand this.


Solution

  • std::allocator is just one possible implementation of the Allocator concept. There are more allocator types in the standard library and users can write their own type satisfying the Allocator concept and the allocator-aware standard library types such as std::vector will work with these allocators in place of std::allocator as well.

    The Allocator concept requires these typedefs because it is not required that such an allocator implementation uses void* as void pointer or value_type* as pointer type. As you can see on the page I linked above, they only need to satisfy some concepts such as e.g. NullablePointer that makes them behave similar to native raw pointers.

    The idea is that you can implement allocators with so-called fancy pointers that have different functionality than native raw pointers. One example for such a pointer type is boost::interprocess::offset_ptr, which is a pointer-like type that points at an offset of itself instead of an absolute address. This is useful if you want to store containers in memory shared between processes. Because every process will map the shared memory pages at a different base virtual address in their respective address space, an absolute native pointer couldn't refer to the intended location in all processes at the same time.

    Technically, because every user of an Allocator is supposed to access it through the std::allocator_traits interface which provides defaults for these typedefs, it is usually not required to actually declare them in the allocator type itself if you want the defaults that you listed. (Except for value_type which doesn't have a default and must always be declared.)

    However std::allocator_traits has been added only in C++11 and std::allocator has always existed. So removing the typedefs is an incompatible change. Therefore they have only been deprecated in C++17 and removed in C++20 from std::allocator (except for value_type).