|
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Defined in header <memory> | ||
Call signature | ||
template<std::destructible T> constexprvoid destroy_at( T* p)noexcept; | (since C++20) | |
IfT is not an array type, calls the destructor of the object pointed to byp, as if byp->~T(). Otherwise, recursively destroys elements of*p in order, as if by callingstd::destroy(std::begin(*p),std::end(*p)).
The function-like entities described on this page arealgorithm function objects (informally known asniebloids), that is:
Contents |
| p | - | a pointer to the object to be destroyed |
struct destroy_at_fn{template<std::destructible T>constexprvoid operator()(T* p)constnoexcept{ifconstexpr(std::is_array_v<T>)for(auto& elem:*p) operator()(std::addressof(elem));else p->~T();}}; inlineconstexpr destroy_at_fn destroy_at{}; |
destroy_at deduces the type of object to be destroyed and hence avoids writing it explicitly in the destructor call.
Whendestroy_at is called in the evaluation of someconstant expressione, the argumentp must point to an object whose lifetime began within the evaluation ofe.
The following example demonstrates how to useranges::destroy_at 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)); for(int i=0; i!=8;++i) std::ranges::destroy_at(ptr+ i);}
Output:
0 destructed1 destructed2 destructed3 destructed4 destructed5 destructed6 destructed7 destructed
(C++20) | destroys a range of objects (algorithm function object)[edit] |
(C++20) | destroys a number of objects in a range (algorithm function object)[edit] |
(C++20) | creates an object at a given address (algorithm function object)[edit] |
(C++17) | destroys an object at a given address (function template)[edit] |