Namespaces
Variants

std:: uninitialized_value_construct_n

From cppreference.net
Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
헤더 파일에 정의됨 <memory>
template < class NoThrowForwardIt, class Size >

NoThrowForwardIt uninitialized_value_construct_n

( NoThrowForwardIt first, Size count ) ;
(1) (C++17부터)
(C++26부터 constexpr)
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 ) typename std:: iterator_traits < NoThrowForwardIt > :: value_type 타입의 객체들을 값 초기화 를 통해 생성합니다. 다음과 같이 구현된 것처럼:

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

예외가 초기화 과정 중에 발생하면, 이미 생성된 객체들은 지정되지 않은 순서로 파괴됩니다.
2) (1) 과 동일하지만, policy 에 따라 실행됩니다.
이 오버로드는 다음의 모든 조건이 만족될 때만 오버로드 해결에 참여합니다:

std:: is_execution_policy_v < std:: decay_t < ExecutionPolicy >> true 인 경우.

(C++20 이전)

std:: is_execution_policy_v < std:: remove_cvref_t < ExecutionPolicy >> true 인 경우.

(C++20 이후)

목차

매개변수

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

반환값

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

복잡도

count 에 대해 선형적입니다.

예외

ExecutionPolicy 라는 템플릿 매개변수를 사용하는 오버로드는 다음과 같이 오류를 보고합니다:

  • 알고리즘의 일부로 호출된 함수 실행 중 예외가 발생하고 ExecutionPolicy 표준 정책 중 하나인 경우, std::terminate 가 호출됩니다. 다른 ExecutionPolicy 의 경우 동작은 구현에 따라 정의됩니다.
  • 알고리즘이 메모리 할당에 실패하는 경우, std::bad_alloc 이 throw됩니다.

참고 사항

기능 테스트 매크로 표준 기능
__cpp_lib_raw_memory_algorithms 202411L (C++26) constexpr for 특수화된 메모리 알고리즘 , ( 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

결함 보고서

다음의 동작 변경 결함 보고서들은 이전에 발표된 C++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 올바른 동작
LWG 3870 C++20 이 알고리즘은 const 스토리지에 객체를 생성할 수 있음 허용되지 않음으로 유지

참고 항목

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