Namespaces
Variants

std::uninitialized_value_construct_n

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

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


 
 
헤더 <memory>
template< class NoThrowForwardIt, class Size >
NoThrowForwardIt uninitialized_value_construct_n
    ( NoThrowForwardIt first, Size count );
에 정의됨 (1) (C++17부터)
(constexpr은 C++26부터)
template< class ExecutionPolicy, class NoThrowForwardIt, class Size >
NoThrowForwardIt uninitialized_value_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)(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_value_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 <iostream>
#include <memory>
#include <string>
int main()
{
    struct S { std::string m{"Default value"}; };
    constexpr int n{3};
    alignas(alignof(S)) unsigned char mem[n * sizeof(S)];
    try
    {
        auto first{reinterpret_cast<S*>(mem)};
        auto last = std::uninitialized_value_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_value_construct_n은
    // 주어진 초기화되지 않은 메모리 영역을 0으로 초기화합니다.
    int v[]{1, 2, 3, 4};
    for (const int i : v)
        std::cout << i << ' ';
    std::cout << '\n';
    std::uninitialized_value_construct_n(std::begin(v), std::size(v));
    for (const int i : v)
        std::cout << i << ' ';
    std::cout << '\n';
}

출력:

Default value
Default value
Default value
1 2 3 4
0 0 0 0

참고 항목

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