Namespaces
Variants

std::uninitialized_value_construct

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

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


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

for (; first != last; ++first)
    ::new (voidify(*first))
        typename std::iterator_traits<NoThrowForwardIt>::value_type();

초기화 중 예외가 발생하면 이미 생성된 객체들은 지정되지 않은 순서로 소멸됩니다.
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, last - 초기화할 요소들의 범위 를 정의하는 반복자 쌍
policy - 사용할 실행 정책
타입 요구사항
-
NoThrowForwardIt 는 LegacyForwardIterator 요구사항을 충족해야 함
-
NoThrowForwardIt 의 유효한 인스턴스를 통한 증가, 할당, 비교, 간접 참조 연산은 예외를 발생시켜서는 안 됨

예외

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

참고

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

가능한 구현

template<class NoThrowForwardIt>
constexpr void uninitialized_value_construct(NoThrowForwardIt first,
                                             NoThrowForwardIt last)
{
    using Value = typename std::iterator_traits<NoThrowForwardIt>::value_type;
    NoThrowForwardIt current = first;
    try
    {
        for (; current != last; ++current)
        {
            ::new (static_cast<void*>(std::addressof(*current))) Value();
        }
    }
    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{first + n};
        std::uninitialized_value_construct(first, last);
        for (auto it{first}; it != last; ++it)
            std::cout << it->m << '\n';
        std::destroy(first, last);
    }
    catch (...)
    {
        std::cout << "Exception!\n";
    }
    // 스칼라 타입의 경우, uninitialized_value_construct는
    // 주어진 초기화되지 않은 메모리 영역을 0으로 채웁니다.
    int v[]{1, 2, 3, 4};
    for (const int i : v)
        std::cout << i << ' ';
    std::cout << '\n';
    std::uninitialized_value_construct(std::begin(v), std::end(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

참고 항목

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