Namespaces
Variants

std:: destroy

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 < class ForwardIt >
void destroy ( ForwardIt first, ForwardIt last ) ;
(1) (C++17 起)
(C++20 起为 constexpr)
template < class ExecutionPolicy, class ForwardIt >
void destroy ( ExecutionPolicy && policy, ForwardIt first, ForwardIt last ) ;
(2) (C++17 起)
1) 销毁范围 [ first , last ) 内的对象,如同执行
for (; first != last; ++first)
    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, last - 定义待销毁元素 范围 的迭代器对
policy - 要使用的 执行策略
类型要求
-
ForwardIt 必须满足 LegacyForwardIterator 的要求。
-
通过 ForwardIt 的有效实例进行递增、赋值、比较或解引用操作不得抛出异常。

复杂度

first last 之间的距离呈线性关系。

异常

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

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

可能的实现

template<class ForwardIt>
constexpr // 自 C++20 起
void destroy(ForwardIt first, ForwardIt last)
{
    for (; first != last; ++first)
        std::destroy_at(std::addressof(*first));
}

示例

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

#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(ptr, ptr + 8);
}

输出:

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

参见

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