Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why C++17 destroy()/destroy_n() functions run forward (and not backwards)?

Tags:

c++

c++17

In C++17 the destroy() and destroy_n() run the destructor of a range of objects.

However according to cppreference this is done in a forward manner, i.e.,

template< class ForwardIt >
void destroy( ForwardIt first, ForwardIt last )
{
  for (; first != last; ++first)
    std::destroy_at(std::addressof(*first));
}

But destruction of an array is reverse to the order of construction as required by the standard.

So what would be the use-case of destroy() and destroy_n()?

Is there a reason for not being consistent with normal array destruction, or is this a mistake in cppreference?

like image 873
Andreas H. Avatar asked May 22 '18 12:05

Andreas H.


2 Answers

The destroy()/destroy_n() is consistent - but with the standard algorithms. It would bring a lot of unncecessary confusion to add a single algorithm that works backwards. Apart from that, You can always do:

destroy(std::rbegin(array), std::rend(array));

which does exactly what You want and expect while maintaining the style and type requirements of the rest of the algorithms.

One more thing concerning the standard. It only states that the C-style array works this way. There is nothing about vector, map or any other stl container. As destroy function can take any C++ range it is reasonable that it behaves as typical C++ code, not as part of the syntax that is inherited quite long ago.

like image 119
bartop Avatar answered Nov 10 '22 05:11

bartop


This functions require forward iterator which can only be moved forward.

There does not seem to be a requirement for specific order of destruction. With different execution policies the order can be different.

You can pass reverse iterators there if you have at least bidirectional iterators.

like image 22
Maxim Egorushkin Avatar answered Nov 10 '22 05:11

Maxim Egorushkin