Namespaces
Variants

std::uninitialized_default_construct

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

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


 
 
헤더 <memory>
template< class NoThrowForwardIt >
void uninitialized_default_construct( NoThrowForwardIt first,
                                      NoThrowForwardIt last );
에 정의됨 (1) (C++17부터)
(C++26부터 constexpr)
template< class ExecutionPolicy, class NoThrowForwardIt >
void uninitialized_default_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_default_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 <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{first + n};
        std::uninitialized_default_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_default_construct는
    // 일반적으로 주어진 초기화되지 않은 메모리 영역을 0으로 채우지 않습니다.
    int v[]{1, 2, 3, 4};
    const int original[]{1, 2, 3, 4};
    std::uninitialized_default_construct(std::begin(v), std::end(v));
    // CWG 1997이 해결될 때까지 미정의 동작일 수 있습니다.
    // for (const int i : v)
    //     std::cout << i << ' ';
    // 결과는 지정되지 않습니다.
    std::cout <<
        (std::memcmp(v, original, sizeof(v)) == 0 ? "Unmodified\n" : "Modified\n");
}

가능한 출력:

Default value
Default value
Default value
Unmodified

참고 항목

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