Search code examples
c++memory-managementlanguage-lawyerallocatorc++17

Why are are std::allocator's construct and destroy functions deprecated in c++17?


The c++17 specification deprecates the construct and destroy members of the std::allocator object. The working group provided rationale for deprecating other member functions here, under the heading "Deprecate the redundant members of std::allocator".

However they don't mention specifically why those two members are deprecated or what the recommendation is for replacing that functionality. I'm assuming the implication is to use std::allocator_traits::construct instead.

I'm a bit confused about whether implementing construct may actually still be necessary in some cases though because of this comment about std::allocator_traits::construct

Because this function provides the automatic fall back to placement new, the member function construct() is an optional Allocator requirement since C++11.

For custom allocators (e.g. for page-aligned memory using memalign), will falling back to placement new always produce the correct behavior?


Solution

  • The allocator requirements table says that construct(c, args), if provided, must "construct an object of type C at c".

    It says absolutely nothing about 1) what arguments are to be passed to C's constructor or 2) how these arguments are to be passed. That's the allocator's choice, and in fact two allocators in the standard do mess with the arguments before passing them to C's constructor: std::scoped_allocator_adaptor and std::pmr::polymorphic_allocator. When constructing a std::pair, in particular, the arguments they pass to pair's constructor may not even resemble the ones they received.

    There's no requirement to perfectly forward, either; a C++03-style construct(T*, const T&) is conforming if inefficient.

    std::allocator's construct and destroy are deprecated because they are useless: no good C++11 and later code should ever call them directly, and they add nothing over the default.


    Handling memory alignment should be the task of allocate, not construct.