|
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Defined in header <memory> | ||
Call signature | ||
template<no-throw-input-iterator I> requiresstd::destructible<std::iter_value_t<I>> | (since C++20) | |
Destroys then objects in the range starting atfirst, equivalent to
return std::ranges::destroy(std::counted_iterator(first, n),std::default_sentinel).base();
The function-like entities described on this page arealgorithm function objects (informally known asniebloids), that is:
Contents |
| first | - | the beginning of the range of elements to destroy |
| n | - | the number of elements to destroy |
The end of the range of objects that has been destroyed.
Linear inn.
struct destroy_n_fn{template<no-throw-input-iterator I> requiresstd::destructible<std::iter_value_t<I>>constexpr I operator()(I first,std::iter_difference_t<I> n)constnoexcept{for(; n!=0;(void)++first,--n) std::ranges::destroy_at(std::addressof(*first));return first;}}; inlineconstexpr destroy_n_fn destroy_n{}; |
The following example demonstrates how to useranges::destroy_n to destroy a contiguous sequence of elements.
#include <iostream>#include <memory>#include <new> struct Tracer{int value; ~Tracer(){std::cout<< value<<" destructed\n";}}; int main(){ alignas(Tracer)unsignedchar buffer[sizeof(Tracer)*8]; for(int i=0; i!=8;++i) new(buffer+ sizeof(Tracer)* i) Tracer{i};// manually construct objects auto ptr=std::launder(reinterpret_cast<Tracer*>(buffer)); std::ranges::destroy_n(ptr,8);}
Output:
0 destructed1 destructed2 destructed3 destructed4 destructed5 destructed6 destructed7 destructed
(C++20) | destroys an object at a given address (algorithm function object)[edit] |
(C++20) | destroys a range of objects (algorithm function object)[edit] |
(C++17) | destroys a number of objects in a range (function template)[edit] |