Namespaces
Variants

std::ranges:: 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 < no-throw-input-iterator I, no - throw - sentinel - for < I > S >

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

constexpr I destroy ( I first, S last ) noexcept ;
(1) (C++20 起)
template < no-throw-input-range R >

requires std:: destructible < ranges:: range_value_t < R >>

constexpr ranges:: borrowed_iterator_t < R > destroy ( R && r ) noexcept ;
(2) (C++20 起)
1) 销毁范围 [ first , last ) 内的对象,操作等效于
for (; first != last; ++first)
    std::ranges::destroy_at(std::addressof(*first));
return first;
2) (1) 相同,但使用 r 作为源范围,如同使用 ranges:: begin ( r ) 作为 first ,以及 ranges:: end ( r ) 作为 last

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

目录

参数

first, last - 定义待销毁元素 范围 的迭代器-哨位对
r - 待销毁的 range 对象

返回值

当迭代器与 last 相等时。

复杂度

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

可能的实现

struct destroy_fn
{
    template<no-throw-input-iterator I, no-throw-sentinel-for<I> S>
        requires std::destructible<std::iter_value_t<I>>
    constexpr I operator()(I first, S last) const noexcept
    {
        for (; first != last; ++first)
            std::ranges::destroy_at(std::addressof(*first));
        return first;
    }
    template<no-throw-input-range R>
        requires std::destructible<std::ranges::range_value_t<R>>
    constexpr std::ranges::borrowed_iterator_t<R> operator()(R&& r) const noexcept
    {
        return operator()(std::ranges::begin(r), std::ranges::end(r));
    }
};
inline constexpr destroy_fn destroy{};

示例

以下示例演示了如何使用 ranges::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::ranges::destroy(ptr, ptr + 8);
}

输出:

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

参见

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