std::ranges::destroy_n - cppreference.com

From cppreference.com

Defined in header

<memory>

Call signature

template</*nothrow-input-iterator*/I>requiresstd::destructible<std::iter_value_t<I>>constexprIdestroy_n(Ifirst,std::iter_difference_t<I>count)noexcept; (1) (since C++20)template</*execution-policy*/Ep,/*nothrow-random-access-iterator*/I>requiresstd::destructible<std::iter_value_t<I>>Idestroy_n(Ep&&policy,Ifirst,std::iter_difference_t<I>count); (2) (since C++26)For the definition of /*execution-policy*/, see

this page

; for the definition of other exposition-only concepts, see

this page

.

1) Destroys elements in the target range first + [0, count) as if by

returnstd::ranges::destroy(std::counted_iterator(first,count),std::default_sentinel).base();2) Same as (1), but executed according to policy.

The function-like entities described on this page are

algorithm function objects

(informally known as niebloids), that is:

Explicit template argument lists cannot be specified when calling any of them.

None of them are visible to

argument-dependent lookup

.

When any of them are found by

normal unqualified lookup

as the name to the left of the function-call operator,

argument-dependent lookup

is inhibited.

Parameters

first - the beginning of the range of elements to destroy count - the number of elements to destroy policy - the

execution policy

to use Return value

As described above.

Notes

Feature-test

macro ValueStdFeature

__cpp_lib_parallel_algorithm

202506L

(C++26)Parallel range algorithms Possible implementation

structdestroy_n_fn{template</*nothrow-input-iterator*/I>requiresstd::destructible<std::iter_value_t<I>>constexprIoperator()(Ifirst,std::iter_difference_t<I>n)constnoexcept{for(;n!=0;(void)++first,--n)std::ranges::destroy_at(std::addressof(*first));returnfirst;}};inlineconstexprdestroy_n_fndestroy_n{};Example

Demonstrates how to use ranges::destroy_n to destroy a contiguous sequence of elements.

Run this code

#include<iostream>#include<memory>#include<new>structTracer{intvalue;~Tracer(){std::cout<<value<<" destructed\n";}};intmain(){alignas(Tracer)unsignedcharbuffer[sizeof(Tracer)*4];for(inti=0;i<4;++i)new(buffer+sizeof(Tracer)*i)Tracer{i};// manually construct objectsautoptr=std::launder(reinterpret_cast<Tracer*>(buffer));std::ranges::destroy_n(ptr,4);}Output:

0 destructed 1 destructed 2 destructed 3 destructed See also