z32a7ul z32a7ul - 3 months ago 25
C++ Question

C++ std::tuple order of destruction

Is there a rule which states in which order the members of an std::tuple are destroyed?

For example if

Function1
returns an
std::tuple<std::unique_ptr<ClassA>, std::unique_ptr<ClassB>>
to
Function2
, then can I be sure that (when the scope of
Function2
is left) the instance of
ClassB
referred to by the second member is destroyed before the instance of
ClassA
referred to by the first member?

std::tuple< std::unique_ptr< ClassA >, std::unique_ptr< ClassB > > Function1()
{
std::tuple< std::unique_ptr< ClassA >, std::unique_ptr< ClassB > > garbage;
get<0>(garbage).reset( /* ... */ );
get<1>(garbage).reset( /* ... */ );
return garbage;
}

void Function2()
{
auto to_be_destroyed = Function1();
// ... do something else

// to_be_destroyed leaves scope
// Is the instance of ClassB destroyed before the instance of ClassA?
}

Answer

The standard doesn't specify the order of destruction for std::tuple. The fact that ยง20.4.1/p1 specifies that:

An instantiation of tuple with two arguments is similar to an instantiation of pair with the same two arguments.

Similar here is not interpreted as identical and consequently it's not implied that std::tuple should have a reverse destruction order of its arguments.

Given the recursive nature of std::tuple most probable is that the order of destruction is in order with the order of its arguments.

I also base my assumptions on a bug report for GCC BUG 66699 where in the discussion my assumptions above are justified.

That said, the order of destruction for std::tuple is unspecified.