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

  • A+

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?

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.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: