Namespaces
Variants

std::ranges:: destroy_at

From cppreference.net
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* )
( 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)
定义于头文件 <memory>
调用签名
template < std:: destructible T >
constexpr void destroy_at ( T * p ) noexcept ;
(C++20 起)

如果 T 不是数组类型,则调用由 p 指向的对象的析构函数,如同通过 p - > ~T ( ) 。否则,按顺序递归销毁 * p 的元素,如同通过调用 std:: destroy ( std:: begin ( * p ) , std:: end ( * p ) )

本页面描述的函数式实体是 算法函数对象 (非正式称为 niebloids ),即:

目录

参数

p - 指向待销毁对象的指针

可能实现

struct destroy_at_fn
{
    template<std::destructible T>
    constexpr void operator()(T* p) const noexcept
    {
        if constexpr (std::is_array_v<T>)
            for (auto& elem : *p)
                operator()(std::addressof(elem));
        else
            p->~T();
    }
};
inline constexpr destroy_at_fn destroy_at{};

注释

destroy_at 会自动推导需要销毁的对象的类型,从而避免在析构函数调用中显式写出该类型。

当在某个 常量表达式 e 的求值过程中调用 destroy_at 时,实参 p 必须指向其生存期始于 e 求值过程内的对象。

示例

以下示例演示如何使用 ranges::destroy_at 销毁连续序列中的元素。

#include <iostream>
#include <memory>
#include <new>
struct Tracer
{
    int value;
    ~Tracer() { std::cout << value << " destructed\n"; }
};
int main()
{
    alignas(Tracer) unsigned char buffer[sizeof(Tracer) * 8];
    for (int i = 0; i != 8; ++i)
        new(buffer + sizeof(Tracer) * i) Tracer{i}; // 手动构造对象
    auto ptr = std::launder(reinterpret_cast<Tracer*>(buffer));
    for (int i = 0; i != 8; ++i)
        std::ranges::destroy_at(ptr + i);
}

输出:

0 destructed
1 destructed
2 destructed
3 destructed
4 destructed
5 destructed
6 destructed
7 destructed

参见

销毁一个对象范围
(算法函数对象)
销毁范围内指定数量的对象
(算法函数对象)
在指定地址创建对象
(算法函数对象)
(C++17)
销毁指定地址的对象
(函数模板)