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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With