Namespaces
Variants

std:: 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>
(1)
template < class ForwardIt, class Size >
ForwardIt destroy_n ( ForwardIt first, Size n ) ;
(C++17 起)
(C++20 前)
template < class ForwardIt, class Size >
constexpr ForwardIt destroy_n ( ForwardIt first, Size n ) ;
(C++20 起)
template < class ExecutionPolicy, class ForwardIt, class Size >
ForwardIt destroy_n ( ExecutionPolicy && policy, ForwardIt first, Size n ) ;
(2) (C++17 起)
1) 销毁从 first 开始的范围内 n 个对象,如同执行
for (; n > 0; (void) ++first, --n)
    std::destroy_at(std::addressof(*first));
2) (1) 相同,但根据 policy 执行。此重载仅当满足以下所有条件时才参与重载决议:

std:: is_execution_policy_v < std:: decay_t < ExecutionPolicy >> true

(C++20 前)

std:: is_execution_policy_v < std:: remove_cvref_t < ExecutionPolicy >> true

(C++20 起)

目录

参数

first - 要销毁的元素范围的起始位置
n - 要销毁的元素数量
policy - 使用的 执行策略
类型要求
-
ForwardIt 必须满足 LegacyForwardIterator 的要求。
-
通过 ForwardIt 的有效实例进行递增、赋值、比较或解引用操作不得抛出异常。

返回值

已被销毁对象范围的末尾(即 std:: next ( first, n ) )。

复杂度

线性于 n

异常

带有名为 ExecutionPolicy 模板参数的重载按以下方式报告错误:

  • 如果作为算法一部分调用的函数执行抛出异常,且 ExecutionPolicy 标准策略 之一,则调用 std::terminate 。对于其他任何 ExecutionPolicy ,其行为由实现定义。
  • 如果算法无法分配内存,将抛出 std::bad_alloc

可能的实现

template<class ForwardIt, class Size>
constexpr // 自 C++20 起
ForwardIt destroy_n(ForwardIt first, Size n)
{
    for (; n > 0; (void) ++first, --n)
        std::destroy_at(std::addressof(*first));
    return first;
}

示例

以下示例演示如何使用 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}; // 手动构造对象
    auto ptr = std::launder(reinterpret_cast<Tracer*>(buffer));
    std::destroy_n(ptr, 8);
}

输出:

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

参见

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