std::destroy_at - cppreference.com

From cppreference.com

Defined in header

<memory>

template<classT>voiddestroy_at(T*p);(since C++17)
(until C++20)template<classT>constexprvoiddestroy_at(T*p);(since C++20)If T is not an array type, calls the destructor of the object pointed to by p, as if by p->~T().

If T is an array type, the program is ill-formed(until C++20)recursively destroys elements of *p in order, as if by calling std::destroy(std::begin(*p),std::end(*p))(since C++20).

Parameters

p - a pointer to the object to be destroyed Possible implementation

template<classT>constexprvoiddestroy_at(T*p){ifconstexpr(std::is_array_v<T>)for(auto&elem:*p)(destroy_at)(std::addressof(elem));elsep->~T();}// C++17 version:// template<class T> void destroy_at(T* p) { p->~T(); }Notes

destroy_at deduces the type of object to be destroyed and hence avoids writing it explicitly in the destructor call.

When destroy_at is called in the evaluation of some

constant expression

e, the argument p must point to an object whose lifetime began within the evaluation of e.

(since C++20)Example

Demonstrates how to use destroy_at 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));for(inti=0;i<4;++i)std::destroy_at(ptr+i);}Output:

0 destructed 1 destructed 2 destructed 3 destructed See also

destroy

(C++17)

destroys a range of objects
(function template & algorithm function object)

[edit]

ranges::destroy

(C++20)

destroy_n

(C++17)

destroys a number of objects in a range
(function template & algorithm function object)

[edit]

ranges::destroy_n

(C++20)

construct_at

(C++20)

creates an object at a given address
(function template & algorithm function object)

[edit]

ranges::construct_at

(C++20)

ranges::destroy_at

(C++20)

destroys an object at a given address
(algorithm function object)

[edit]