命名空间
变体
操作

std::ranges::destroy_at

来自 cppreference.cn
< cpp‎ | memory
 
 
内存管理库
(仅为阐释目的*)
未初始化内存算法
(C++17)
(C++17)
(C++17)
受约束的未初始化
内存算法
ranges::destroy_at
(C++20)
C 库

分配器
内存资源
垃圾回收支持
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
未初始化存储
(直到 C++20*)
(直到 C++20*)
显式生命周期管理
 
定义于头文件 <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),即

内容

[edit] 参数

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

[edit] 返回值

(无)

[edit] 可能的实现

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{};

[edit] 注解

destroy_at 推导要销毁的对象的类型,因此避免在析构函数调用中显式编写它。

当在某个 常量表达式 e 的求值中调用 destroy_at 时,实参 p 必须指向生命周期在 e 的求值中开始的对象。

[edit] 示例

以下示例演示如何使用 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}; //manually construct objects
 
    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

[edit] 参见

销毁某个范围的对象
(算法函数对象)[编辑]
销毁某个范围内若干个对象
(算法函数对象)[编辑]
在给定地址创建对象
(算法函数对象)[编辑]
在给定地址销毁对象
(函数模板) [编辑]