27

Does ISO C++ standard mandate any sort of destruction order of objects inside STL containers?

  • Are std::list/std::vector/std::map elements destroyed starting from the beginning or the end of the container?
  • Can I rely on std::map storing its elements in std::pairs internally so a key in a pair is destroyed before its value (or vice versa)?
Alex B
  • 82,554
  • 44
  • 203
  • 280
  • It is probably unspecified, but for `std::list` is for sure either in order or in reverse order since there is no other way to go through the elements (without doing extra work). – alfC Feb 10 '21 at 02:55

2 Answers2

24
  1. Unspecified in the standard.
  2. Yes, but this means that the key is destroyed after its associated value.
  • #2, yep, that's what I meant, should've written the other way around. Can you point me to the part of the standard that specifies #2? – Alex B Jan 18 '10 at 02:59
  • 20.2.2/1, and this ties in with my comments on Terry's answer. –  Jan 18 '10 at 03:01
  • @Roger Pate: Include that in the answer and I'll accept it. :) – Alex B Jan 19 '10 at 01:49
5
  1. Unspecified
  2. Yes, you can depend on std::map storing it's elements in std::pairs, but I don't see anything which specifies the Key portion of a std::pair being destructed before a Value portion.
Terry Mahaffey
  • 11,775
  • 1
  • 35
  • 44
  • 3
    The standard mandates *first* and *second* data members and shows them in that order, which, if that order is required, also determines construction and destruction order. –  Jan 18 '10 at 02:49
  • I can't find anything that explicitly says that order is required, but also nothing that says it is allowed to be different. As they're public members and definitely not marked "exposition only", none of the other clauses granting leeway to the implementation apply. So, I'm going to have to fall on the side of that being the required order. –  Jan 18 '10 at 03:03
  • Looking at the draft C++0x standard, it does appear that that standard mandates that *first* be constructed prior to *second*. Specifically, 20.3.3.4 `pair(); Effects: Initializes its members as if implemented: pair() : first(), second() {}` I read that to mean order is defined, but I'll defer to a language lawyer. – R Samuel Klatchko Jan 18 '10 at 03:04
  • 2
    @RSK: 20.2.2/1 is a stronger ordering requirement - the order in an initialization list doesn't influence and (unfortunately) doesn't need to match the actual initialization order, which is specified by the class member declaration. – Michael Burr Jan 18 '10 at 03:10
  • 3
    @RSamuel: The order in the ctor initializer doesn't matter, it's member declaration order that determines initialization order. (And almost identical text is in the current standard at 20.2.2/2.) –  Jan 18 '10 at 03:11
  • @MichaelBurr And destruction order is specified to be opposite of initialization order, right? – Mark Ransom Jan 09 '19 at 20:28