Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the order of destruction of the two entries of a std::pair?

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

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?

like image 317
Enlico Avatar asked Aug 31 '25 01:08

Enlico


1 Answers

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.

like image 160
j6t Avatar answered Sep 02 '25 16:09

j6t