memory_uninitialized_default_construct
memory_uninitialized_default_construct (std::uninitialized_default_construct)
<memory> 헤더에 정의되어 있어요. 대상 범위 [first, last)의 요소를 기본 초기화(default-initialization)로 구성해요. C++17부터 도입됐어요.
출처: cppreference
본문
template< class NoThrowForwardIt >
void uninitialized_default_construct( NoThrowForwardIt first, NoThrowForwardIt last ); // (1) since C++17, constexpr since C++26
template< class ExecutionPolicy, class NoThrowForwardIt >
void uninitialized_default_construct( ExecutionPolicy&& policy, NoThrowForwardIt first, NoThrowForwardIt last ); // (2) since C++17
- (1) 대상 범위
[first, last)의 요소를 기본 초기화로 다음과 같이 구성해요.
for (; first != last; ++first)
::new (voidify(*first))
typename std::iterator_traits<NoThrowForwardIt>::value_type;
초기화 중 예외가 발생하면 이미 구성된 객체들이 미지정 순서로 파괴돼요.
- (2) (1)과 같지만
policy에 따라 실행돼요. (C++17)
매개변수
first, last: 초기화할 요소 범위를 정의하는 반복자 쌍policy: 사용할 실행 정책
예제
#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"; }
}
가능한 출력:
Default value
Default value
Default value