Namespaces
Variants

std::ranges::uninitialized_default_construct_n

cppreference.net에서
 
 
알고리즘 라이브러리
제약 알고리즘 및 ranges 알고리즘 (C++20)
제약 알고리즘, 예: ranges::copy, ranges::sort, ...
정렬 및 관련 연산
분할 연산
(C++11)    

정렬 연산
이진 탐색 연산
(분할된 범위에서)
집합 연산 (정렬된 범위에서)
병합 연산 (정렬된 범위에서)
힙 연산
최소/최대 연산
(C++11)
(C++17)
사전식 비교 연산
순열 연산


 
 
헤더 <memory>
에 정의됨
template< /*nothrow-forward-iterator*/ I >
    requires std::default_initializable<std::iter_value_t<I>>
I uninitialized_default_construct_n( I first,
                                     std::iter_difference_t<I> count );
호출 시그니처 (C++20부터)
(constexpr은 C++26부터)
template< /*execution-policy*/ Ep, /*nothrow-random-access-iterator*/ I >
    requires std::default_initializable<std::iter_value_t<I>>
I uninitialized_default_construct_n( Ep&& policy, I first,
                                     std::iter_difference_t<I> count );
(2) (C++26부터)

/*execution-policy*/의 정의는 이 페이지를 참조하십시오; 다른 설명 전용 컨셉의 정의는 이 페이지를 참조하십시오.

1) 대상 범위 first + [0, count)의 요소들을 기본 초기화로 다음과 같이 생성합니다.

return ranges::uninitialized_default_construct(std::counted_iterator(first, count),
                                               std::default_sentinel).base();

초기화 중 예외가 발생하면 이미 생성된 객체들은 지정되지 않은 순서로 소멸됩니다.
2)(1)과 동일하지만, policy에 따라 실행됩니다.

이 페이지에 설명된 함수형 엔티티는 알고리즘 함수 객체 (비공식적으로 니블로이드라고도 함)입니다. 즉:

매개변수

first - 초기화할 요소 범위의 시작
count - 생성할 요소의 개수
policy - 해당 실행 정책 사용할

반환값

위에서 설명한 바와 같습니다.

예외

대상 범위의 요소를 생성하는 중에 발생한 모든 예외.

2) 실행 과정 중:
  • 병렬화에 필요한 임시 메모리 자원을 사용할 수 없는 경우, std::bad_alloc 이 발생합니다.
  • 알고리즘 인수를 통해 객체에 접근하는 중에 처리되지 않은 예외가 발생하면, 그 동작은 실행 정책에 의해 결정됩니다 (표준 정책의 경우, std::terminate 이 호출됩니다).

참고

구현은 (관찰 가능한 효과를 변경하지 않고) std::iter_value_t<I> 객체를 기본 초기화하는 동안 비사소한 기본 생성자가 호출되지 않으면 객체 생성을 건너뛸 수 있습니다. 이는 std::is_trivially_default_constructible로 감지할 수 있습니다.

기능 테스트 매크로 값 표준 기능
__cpp_lib_parallel_algorithm 202506L (C++26) 병렬 범위 알고리즘
__cpp_lib_raw_memory_algorithms 202411L (C++26) constexpr을 위한 특화된 <memory> 알고리즘, (1)

가능한 구현

struct uninitialized_default_construct_n_fn
{
    template</*nothrow-forward-iterator*/ I>
        requires std::default_initializable<std::iter_value_t<I>>
    constexpr I operator()(I first, std::iter_difference_t<I> count) const
    {
        auto iter = std::counted_iterator(first, count);
        return ranges::uninitialized_default_construct(iter, std::default_sentinel).base();
    }
};

inline constexpr uninitialized_default_construct_n_fn uninitialized_default_construct_n{};

예제

#include <cstring>
#include <iostream>
#include <memory>
#include <string>

int main()
{
    struct S { std::string m{"█▓▒░ █▓▒░ "}; };
    
    constexpr int n{4};
    alignas(alignof(S)) char out[n * sizeof(S)];
    
    try
    {
        auto first{reinterpret_cast<S*>(out)};
        auto last = std::ranges::uninitialized_default_construct_n(first, n);
        
        auto count{1};
        for (auto it{first}; it != last; ++it)
            std::cout << count++ << ' ' << it->m << '\n';
        
        std::ranges::destroy(first, last);
    }
    catch (...)
    {
        std::cout << "Exception!\n";
    }
    
    // For scalar types, uninitialized_default_construct_n
    // generally does not zero-fill the given uninitialized memory area.
    constexpr int sample[]{1, 2, 3, 4, 5, 6};
    int v[]{1, 2, 3, 4, 5, 6};
    std::ranges::uninitialized_default_construct_n(std::begin(v), std::size(v));
    if (std::memcmp(v, sample, sizeof(v)) == 0)
    {
        // Maybe undefined behavior, pending CWG 1997:
        // for (const int i : v) { std::cout << i << ' '; }
        for (const int i : sample)
            std::cout << i << ' ';
    }
    else
        std::cout << "Unspecified!";
    std::cout << '\n';
}

가능한 출력:

1 █▓▒░ █▓▒░
2 █▓▒░ █▓▒░
3 █▓▒░ █▓▒░
4 █▓▒░ █▓▒░
1 2 3 4 5 6

같이 보기

범위로 정의된 초기화되지 않은 메모리 영역에 객체를 기본 초기화하여 생성합니다
(알고리즘 함수 객체)
범위로 정의된 초기화되지 않은 메모리 영역에 객체를 값 초기화하여 생성합니다
(알고리즘 함수 객체)
시작과 개수로 정의된 초기화되지 않은 메모리 영역에 객체를 값 초기화하여 생성합니다
(알고리즘 함수 객체)
시작과 개수로 정의된 초기화되지 않은 메모리 영역에 객체를 기본 초기화하여 생성합니다
(함수 템플릿)