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)
Definido en el encabezado <memory>
Firma de llamada
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 ;
(desde C++20)

Destruye los n objetos en el rango que comienza en first , equivalente a

Las entidades similares a funciones descritas en esta página son algorithm function objects (conocidas informalmente como niebloids ), es decir:

Contenidos

Parámetros

first - el inicio del rango de elementos a destruir
n - el número de elementos a destruir

Valor de retorno

El final del rango de objetos que ha sido destruido.

Complejidad

Lineal en n .

Implementación posible

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

Ejemplo

El siguiente ejemplo demuestra cómo usar ranges::destroy_n para destruir una secuencia contigua de elementos.

#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);
}

Salida:

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

Véase también

destruye un objeto en una dirección dada
(objeto función de algoritmo)
destruye un rango de objetos
(objeto función de algoritmo)
(C++17)
destruye una cantidad de objetos en un rango
(plantilla de función)