std::ranges::destroy_n

From cppreference.com
< cpp‎ | memory
 
 
Utilities library
General utilities
Date and time
Function objects
Formatting library (C++20)
(C++11)
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)(C++20)(C++20)   
(C++20)
Swap and type operations
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
Elementary string conversions
(C++17)
(C++17)
 
Dynamic memory management
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Allocators
Garbage collection support
(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)



 
Defined in header <memory>
Call signature
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;
(since C++20)

Destroys the n objects in the range starting at first, equivalent to

The function-like entities described on this page are niebloids, that is:

In practice, they may be implemented as function objects, or with special compiler extensions.

Parameters

first - the beginning of the range of elements to destroy
n - the number of elements to destroy

Return value

The end of the range of objects that has been destroyed.

Complexity

Linear in n.

Possible implementation

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

Example

The following example demonstrates how to use ranges::destroy_n to destroy a contiguous sequence of elements.

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

Output:

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

See also

destroys an object at a given address
(niebloid)
destroys a range of objects
(niebloid)
(C++17)
destroys a number of objects in a range
(function template)