views:

151

answers:

2

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)?
+3  A: 
  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
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.
Roger Pate
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.
Roger Pate
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
@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
@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.)
Roger Pate
+6  A: 
  1. Unspecified in the standard.
  2. Yes, but this means that the key is destroyed after its associated value.
Roger Pate
+1 ............ :)
Prasoon Saurav
#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
20.2.2/1, and this ties in with my comments on Terry's answer.
Roger Pate
@Roger Pate: Include that in the answer and I'll accept it. :)
Alex B