Namespaces
Variants

std::ranges:: destroy_n

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 < no-throw-input-iterator I >

requires std:: destructible < std:: iter_value_t < I >>

constexpr I destroy_n ( I first, std:: iter_difference_t < I > n ) noexcept ;
(C++20 起)

销毁从 first 开始的范围内 n 个对象,相当于

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

目录

参数

first - 要销毁的元素范围的起始位置
n - 要销毁的元素数量

返回值

已被销毁对象范围的末端。

复杂度

线性于 n

可能的实现

struct destroy_n_fn
{
    template<no-throw-input-iterator I>
        requires std::destructible<std::iter_value_t<I>>
    constexpr I operator()(I first, std::iter_difference_t<I> n) const noexcept
    {
        for (; n != 0; (void)++first, --n)
            std::ranges::destroy_at(std::addressof(*first));
        return first;
    }
};
inline constexpr destroy_n_fn destroy_n{};

示例

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

#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));
    std::ranges::destroy_n(ptr, 8);
}

输出:

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

参见

销毁给定地址处的对象
(算法函数对象)
销毁对象范围
(算法函数对象)
(C++17)
销毁范围内的多个对象
(函数模板)