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)
헤더 파일에 정의됨 <memory>
호출 시그니처
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 ;
(C++20부터)

범위의 시작점 first 에서 시작하는 n 개의 객체를 파괴하며, 다음 코드와 동일합니다:

이 페이지에서 설명하는 함수형 개체들은 algorithm function objects (일반적으로 niebloids 로 알려진) 즉:

목차

매개변수

first - 파괴할 요소 범위의 시작
n - 파괴할 요소의 개수

반환값

파괴된 객체 범위의 끝을 나타냅니다.

복잡도

n 에 대해 선형적입니다.

가능한 구현

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

예제

다음 예제는 연속된 요소 시퀀스를 파괴하기 위해 ranges::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}; // manually construct objects
    auto ptr = std::launder(reinterpret_cast<Tracer*>(buffer));
    std::ranges::destroy_n(ptr, 8);
}

출력:

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

참고 항목

주어진 주소의 객체를 파괴함
(알고리즘 함수 객체)
객체 범위를 파괴함
(알고리즘 함수 객체)
(C++17)
범위 내의 여러 객체를 파괴함
(함수 템플릿)