Namespaces
Variants

std::ranges:: uninitialized_value_construct

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 < no-throw-forward-iterator I, no - throw - sentinel - for < I > S >

requires std:: default_initializable < std:: iter_value_t < I >>

I uninitialized_value_construct ( I first, S last ) ;
(1) (C++20부터)
(C++26부터 constexpr)
template < no-throw-forward-range R >

requires std:: default_initializable < ranges:: range_value_t < R >>
ranges:: borrowed_iterator_t < R >

uninitialized_value_construct ( R && r ) ;
(2) (C++20부터)
(C++26부터 constexpr)
1) 초기화되지 않은 메모리 영역 [ first , last ) 에서 std:: iter_value_t < I > 타입의 객체들을 값 초기화 를 통해 생성합니다. 다음과 같이 구현된 것처럼:

for ( ; first ! = last ; ++ first )
:: new ( voidify ( * first ) )
std:: remove_reference_t < std:: iter_reference_t < I >> ( ) ;
return first ;

예외가 초기화 과정에서 발생하면, 이미 생성된 객체들은 지정되지 않은 순서로 파괴됩니다.
2) 다음과 동일함: ranges :: uninitialized_value_construct ( ranges:: begin ( r ) , ranges:: end ( r ) ) .

이 페이지에서 설명하는 함수형 개체들은 algorithm function objects (일반적으로 niebloids 로 알려진) 즉:

목차

매개변수

first, last - 값 초기화할 요소들의 범위 를 정의하는 반복자-감시자 쌍
r - 값 초기화할 요소들의 range 범위

반환값

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

복잡도

first last 사이의 거리에 선형적으로 비례합니다.

예외

대상 범위의 요소 생성 과정에서 발생하는 모든 예외.

참고 사항

구현은 범위의 값 타입이 CopyAssignable TrivialType 인 경우, 예를 들어 ranges::fill 을 사용함으로써 ranges::uninitialized_value_construct 의 효율을 향상시킬 수 있습니다.

기능 테스트 매크로 표준 기능
__cpp_lib_raw_memory_algorithms 202411L (C++26) constexpr for 특수화된 메모리 알고리즘 , ( 1,2 )

가능한 구현

struct uninitialized_value_construct_fn
{
    template<no-throw-forward-iterator I, no-throw-sentinel-for<I> S>
        requires std::value_initializable<std::iter_value_t<I>>
    constexpr I operator()(I first, S last) const
    {
        using ValueType = std::remove_reference_t<std::iter_reference_t<I>>;
        if constexpr (std::is_trivially_default_constructible_v<ValueType>)
            return ranges::fill(first, last, ValueType());
        I rollback{first};
        try
        {
            for (; !(first == last); ++first)
                ::new (static_cast<void*>(std::addressof(*first))) ValueType();
            return first;
        }
        catch (...) // 롤백: 생성된 요소들 파괴
        {
            for (; rollback != first; ++rollback)
                ranges::destroy_at(std::addressof(*rollback));
            throw;
        }
    }
    template<no-throw-forward-range R>
        requires std::default_initializable<ranges::range_value_t<R>>
    constexpr ranges::borrowed_iterator_t<R> operator()(R&& r) const
    {
        return (*this)(ranges::begin(r), ranges::end(r));
    }
};
inline constexpr uninitialized_value_construct_fn uninitialized_value_construct{};

예제

#include <iostream>
#include <memory>
#include <string>
int main()
{
    struct S { std::string m{"▄▀▄▀▄▀▄▀"}; };
    constexpr int n{4};
    alignas(alignof(S)) char out[n * sizeof(S)];
    try
    {
        auto first{reinterpret_cast<S*>(out)};
        auto last{first + n};
        std::ranges::uninitialized_value_construct(first, last);
        auto count{1};
        for (auto it{first}; it != last; ++it)
            std::cout << count++ << ' ' << it->m << '\n';
        std::ranges::destroy(first, last);
    }
    catch (...)
    {
        std::cout << "Exception!\n";
    }
    // 스칼라 타입의 경우, uninitialized_value_construct는
    // 주어진 초기화되지 않은 메모리 영역을 0으로 채웁니다.
    int v[]{0, 1, 2, 3};
    std::cout << ' ';
    for (const int i : v)
        std::cout << ' ' << static_cast<char>(i + 'A');
    std::cout << "\n ";
    std::ranges::uninitialized_value_construct(std::begin(v), std::end(v));
    for (const int i : v)
        std::cout << ' ' << static_cast<char>(i + 'A');
    std::cout << '\n';
}

출력:

1 ▄▀▄▀▄▀▄▀
2 ▄▀▄▀▄▀▄▀
3 ▄▀▄▀▄▀▄▀
4 ▄▀▄▀▄▀▄▀
  A B C D
  A A A A

결함 보고서

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

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

참고 항목

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