3

Only 5 tags are allowed, but please, take it as and are in the list too, because I'd like to know about those standards as well, in case something has changed since .

Is the order of destruction of the two entries of a std::pair (not std::tuple, nor other containers) specified by the standard? Where in the standard draft can I find this information?

Also, in case the order is indeed specified, since when has it been?

In my GCC implementation I see this

namespace std {
// ...
  template<typename _T1, typename _T2>
    struct pair
    : private __pair_base<_T1, _T2>
    {
      typedef _T1 first_type;    ///< The type of the `first` member
      typedef _T2 second_type;   ///< The type of the `second` member

      _T1 first;                 ///< The first member
      _T2 second;                ///< The second member
// ...

so it's clear that second is destroyed before first, but is it just a choice of GCC or is it mandated by the standard?


Actually, a quick search in the draft reveals that §22.3.2 shows what the std::pair class looks like, and it starts like this:

namespace std {
  template<class T1, class T2>
  struct pair {
    using first_type  = T1;
    using second_type = T2;

    T1 first;
    T2 second;

Is it just an example? Or is it a mandate?

Enlico
  • 23,259
  • 6
  • 48
  • 102

1 Answers1

4

The order is specified in the Standard:

template<class T1, class T2>
  struct pair {
    using first_type  = T1;
    using second_type = T2;

    T1 first;
    T2 second;
    //...
  }

The definitions of the members are not marked as "exposition only", hence, they are mandatory.

j6t
  • 9,150
  • 1
  • 15
  • 35
  • Yeah, I ended up finding it right before you posted, but thanks. I would actually ask: how do I know that that code is meant to be mandatory and not just an example? Would I have found a not telling it is just an example? – Enlico Jul 27 '23 at 10:51
  • Generally, what's written in the Standard *is* the specification. Occasionally, however, there are blanket statements "We write A to mean B without implying C" in introductory sections. So, you can't be sure about the meaning of a paragraph unless you have read (and understood) the entire text of the Standard. In this particular case, I do not recall that an exception would be made, though. – j6t Jul 27 '23 at 10:59
  • Is a class synopsis like the one you quote actually normative? Because if so, I would expect that the order of the member functions should be respected as well, but both stdlibc++ and libc++ declare them in different orders. Though I suppose it makes no difference for member functions... – Nelfeal Jul 27 '23 at 11:05
  • @Nelfeal, I guess I could ask _Is a class synopsis like the one you quote actually normative?_ as a separate question :D – Enlico Jul 27 '23 at 11:43
  • 2
    @Nelfeal - There is also the "as-if"-rule. Can you detect function declaration order from your program? No? – BoP Jul 27 '23 at 12:13