Search code examples
c++allocator

Are STL containers allowed to skip calling allocator::construct and allocator::destroy if the object is trivially constructible/destructible?


The question is in the title. Is this allowed for containers, or are the allocator's methods guaranteed to be called even when the object is trivially constructible/destructible?

I did try to search for this but came back empty-handed... but if it's a duplicate please let me know.


Solution

  • § 23.2.1 [container.requirements.general]/p3:

    For the components affected by this subclause that declare an allocator_type, objects stored in these components shall be constructed using the allocator_traits<allocator_type>::construct function and destroyed using the allocator_traits<allocator_type>::destroy function (20.7.8.2).

    There's no provision allowing for those calls to be omitted beyond the as-if rule. In fact, I can't find a single instance of the word "trivial" in Clause 23, which specifies the standard library containers.

    As to why they specified type traits like is_trivially_destructible, you'll have to dig out the original proposal paper for the rationale. It's not used in the C++14 standard, but it is currently used to specify std::optional in the draft Library Fundamentals TS:

    ~optional();
    
    • Effects: If is_trivially_destructible<T>::value != true and *this contains a value, calls val->T::~T().

    • Remarks: If is_trivially_destructible<T>::value == true then this destructor shall be a trivial destructor.