Namespaces
Variants

std::uninitialized_default_construct_n

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

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


 
 
헤더 <memory>
template< class NoThrowForwardIt, class Size >
NoThrowForwardIt uninitialized_default_construct_n
    ( NoThrowForwardIt first, Size count );
에 정의됨 (1) (C++17부터)
(C++26부터 constexpr)
template< class ExecutionPolicy, class NoThrowForwardIt, class Size >
NoThrowForwardIt uninitialized_default_construct_n
    ( ExecutionPolicy&& policy, NoThrowForwardIt first, Size count );
(2) (C++17부터)
1) 목적지 범위 first + [0, count) 에 요소들을 기본 초기화로 생성합니다. 마치

for (; count > 0; (void)++first, --count)
    ::new (voidify(*first))
        typename std::iterator_traits<NoThrowForwardIt>::value_type;
return first;

만약 초기화 중 예외가 발생하면, 이미 생성된 객체들은 지정되지 않은 순서로 소멸됩니다.
2) (1)과 동일하지만, policy에 따라 실행됩니다.
이 오버로드는 다음 표현식의 값이 true인 경우에만 오버로드 해결에 참여합니다:

std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>

(C++20까지)

std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>

(C++20부터)

매개변수

first - 초기화할 요소 범위의 시작
count - 생성할 요소의 개수
policy - 사용할 실행 정책
타입 요구사항
-
NoThrowForwardIt 는 LegacyForwardIterator 요구사항을 충족해야 함
-
NoThrowForwardIt 의 유효한 인스턴스를 통한 증가, 할당, 비교, 간접 참조 연산은 예외를 발생시켜서는 안 됨

반환값

위에서 설명한 대로.

예외

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

참고

기능-테스트 매크로 값 표준 기능
__cpp_lib_raw_memory_algorithms 202411L (C++26) constexpr 용 특수 <memory>알고리즘, (1)

가능한 구현

template<class NoThrowForwardIt, class Size>
constexpr ForwardIt uninitialized_default_construct_n(NoThrowForwardIt first, Size count)
{
    using T = typename std::iterator_traits<NoThrowForwardIt>::value_type;
    NoThrowForwardIt current = first;
    try
    {
        for (; countn > 0; (void) ++current, --count)
            ::new (static_cast<void*>(std::addressof(*current))) T;
        return current;
    }
    catch (...)
    {
        std::destroy(first, current);
        throw;
    }
}

예제

#include <cstring>
#include <iostream>
#include <memory>
#include <string>
struct S
{
    std::string m{"default value"};
};
int main()
{
    constexpr int n{3};
    alignas(alignof(S)) unsigned char mem[n * sizeof(S)];
    try
    {
        auto first{reinterpret_cast<S*>(mem)};
        auto last = std::uninitialized_default_construct_n(first, n);
        for (auto it{first}; it != last; ++it)
            std::cout << it->m << '\n';
        std::destroy(first, last);
    }
    catch(...)
    {
        std::cout << "Exception!\n";
    }
    // 스칼라 타입의 경우, uninitialized_default_construct_n은
    // 일반적으로 주어진 초기화되지 않은 메모리 영역을 0으로 초기화하지 않습니다.
    int v[]{1, 2, 3, 4};
    const int original[]{1, 2, 3, 4};
    std::uninitialized_default_construct_n(std::begin(v), std::size(v));
    // v에 접근하려는 시도는 미정의 동작일 수 있으며,
    // CWG 1997이 해결되기를 기다리고 있습니다:
    // for (const int i : v)
    //     std::cout << i << ' ';
    // 결과는 지정되지 않습니다:
    std::cout << (std::memcmp(v, original, sizeof(v)) == 0 ? "un" : "") << "modified\n";
}

가능한 출력:

default value
default value
default value
unmodified

참고 항목

범위로 정의된 초기화되지 않은 메모리 영역에서 default-initialization 방식으로 객체를 생성합니다
(함수 템플릿)
시작점과 개수로 정의된 초기화되지 않은 메모리 영역에서 value-initialization 방식으로 객체를 생성합니다
(함수 템플릿)
시작점과 개수로 정의된 초기화되지 않은 메모리 영역에서 default-initialization 방식으로 객체를 생성합니다
(알고리즘 함수 객체)