|
|
Defined in header <memory> | ||
Call signature | ||
template<no-throw-input-iterator I, no-throw-sentinel-for<I> S> requiresstd::destructible<std::iter_value_t<I>> | (1) | (since C++20) |
template<no-throw-input-range R> requiresstd::destructible<ranges::range_value_t<R>> | (2) | (since C++20) |
[
first,
last)
, as if byfor(; first!= last;++first) std::ranges::destroy_at(std::addressof(*first));return first;
The function-like entities described on this page arealgorithm function objects (informally known asniebloids), that is:
Contents |
first, last | - | the iterator-sentinel pair defining therange of elements to destroy |
r | - | therange to destroy |
An iterator compares equal tolast.
Linear in the distance betweenfirst andlast.
struct destroy_fn{template<no-throw-input-iterator I, no-throw-sentinel-for<I> S> requiresstd::destructible<std::iter_value_t<I>>constexpr I operator()(I first, S last)constnoexcept{for(; first!= last;++first) std::ranges::destroy_at(std::addressof(*first));return first;} template<no-throw-input-range R> requiresstd::destructible<std::ranges::range_value_t<R>>constexpr std::ranges::borrowed_iterator_t<R> operator()(R&& r)constnoexcept{return operator()(std::ranges::begin(r), std::ranges::end(r));}}; inlineconstexpr destroy_fn destroy{}; |
The following example demonstrates how to useranges::destroy
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(ptr, ptr+8);}
Output:
0 destructed1 destructed2 destructed3 destructed4 destructed5 destructed6 destructed7 destructed
(C++20) | destroys a number of objects in a range (algorithm function object)[edit] |
(C++20) | destroys an object at a given address (algorithm function object)[edit] |
(C++17) | destroys a range of objects (function template)[edit] |