Namespaces
Variants

std:: 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>
(1)
template < class ForwardIt, class Size >
ForwardIt destroy_n ( ForwardIt first, Size n ) ;
(C++17부터)
(C++20까지)
template < class ForwardIt, class Size >
constexpr ForwardIt destroy_n ( ForwardIt first, Size n ) ;
(C++20부터)
template < class ExecutionPolicy, class ForwardIt, class Size >
ForwardIt destroy_n ( ExecutionPolicy && policy, ForwardIt first, Size n ) ;
(2) (C++17부터)
1) 범위 시작점 first 에서 시작하는 n 개의 객체를 다음과 같이 파괴합니다:
for (; n > 0; (void) ++first, --n)
    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 - 파괴할 요소 범위의 시작
n - 파괴할 요소의 개수
policy - 사용할 실행 정책
타입 요구사항
-
ForwardIt LegacyForwardIterator 요구사항을 충족해야 함
-
ForwardIt 의 유효한 인스턴스를 통한 증가, 할당, 비교, 간접 참조는 예외를 발생시켜서는 안 됨

반환값

파괴된 객체 범위의 끝 (즉, std:: next ( first, n ) ).

복잡도

n 에 대해 선형적입니다.

예외

ExecutionPolicy 라는 템플릿 매개변수를 사용하는 오버로드는 다음과 같이 오류를 보고합니다:

  • 알고리즘의 일부로 호출된 함수 실행 중 예외가 발생하고 ExecutionPolicy 표준 정책 중 하나인 경우, std::terminate 가 호출됩니다. 다른 ExecutionPolicy 의 경우 동작은 구현에 따라 정의됩니다.
  • 알고리즘이 메모리 할당에 실패할 경우, std::bad_alloc 이 throw됩니다.

가능한 구현

template<class ForwardIt, class Size>
constexpr // C++20부터
ForwardIt destroy_n(ForwardIt first, Size n)
{
    for (; n > 0; (void) ++first, --n)
        std::destroy_at(std::addressof(*first));
    return first;
}

예제

다음 예제는 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::destroy_n(ptr, 8);
}

출력:

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

참고 항목

(C++17)
객체 범위를 파괴합니다
(함수 템플릿)
(C++17)
주어진 주소의 객체를 파괴합니다
(함수 템플릿)
범위 내 지정된 개수의 객체를 파괴합니다
(알고리즘 함수 객체)