Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::destroy_at

      From cppreference.com
      <cpp‎ |memory
       
       
      Memory management library
      (exposition only*)
      Allocators
      Uninitialized memory algorithms
      Constrained uninitialized memory algorithms
      Memory resources
      Uninitialized storage(until C++20)
      (until C++20*)
      (until C++20*)
      Garbage collector support(until C++23)
      (C++11)(until C++23)
      (C++11)(until C++23)
      (C++11)(until C++23)
      (C++11)(until C++23)
      (C++11)(until C++23)
      (C++11)(until C++23)
       
      Defined in header<memory>
      template<class T>
      void destroy_at( T* p);
      (since C++17)
      (constexpr since C++20)

      IfT is not an array type, calls the destructor of the object pointed to byp, as if byp->~T().

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

      Contents

      [edit]Parameters

      p - a pointer to the object to be destroyed

      [edit]Possible implementation

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

      [edit]Notes

      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.

      (since C++20)

      [edit]Example

      The following example demonstrates how to usedestroy_at to destroy a contiguous sequence of elements.

      Run this code
      #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::destroy_at(ptr+ i);}

      Output:

      0 destructed1 destructed2 destructed3 destructed4 destructed5 destructed6 destructed7 destructed

      [edit]See also

      (C++17)
      destroys a range of objects
      (function template)[edit]
      (C++17)
      destroys a number of objects in a range
      (function template)[edit]
      creates an object at a given address
      (function template)[edit]
      destroys an object at a given address
      (algorithm function object)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/memory/destroy_at&oldid=183354"

      [8]ページ先頭

      ©2009-2025 Movatter.jp