Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

allocator

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.

like image 326
user541686 Avatar asked Aug 04 '14 20:08

user541686


1 Answers

§ 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.

like image 108
T.C. Avatar answered Sep 23 '22 07:09

T.C.