memory_uninitialized_copy_n
memory_uninitialized_copy_n (std::uninitialized_copy_n)
<memory> 헤더에 정의되어 있어요. 소스 범위의 처음 count개 요소를 d_first에서 시작하는 대상 범위에 복사해 구성해요. C++11부터 도입됐어요.
출처: cppreference
본문
template< class InputIt, class Size, class NoThrowForwardIt >
NoThrowForwardIt uninitialized_copy_n( InputIt first, Size count, NoThrowForwardIt d_first ); // (1) since C++11, constexpr since C++26
template< class ExecutionPolicy, class ForwardIt, class Size, class NoThrowForwardIt >
NoThrowForwardIt uninitialized_copy_n( ExecutionPolicy&& policy, ForwardIt first, Size count, NoThrowForwardIt d_first ); // (2) since C++17
- (1)
first에서 시작하는 소스 범위의 처음count개 요소를d_first에서 시작하는 대상 범위에 다음과 같이 구성해요.
for (; count > 0; ++d_first, (void) ++first, --count)
::new (voidify(*d_first))
typename std::iterator_traits<NoThrowForwardIt>::value_type(*first);
return d_first;
초기화 중 예외가 발생하면 이미 구성된 객체들이 미지정 순서로 파괴돼요.
- (2) (1)과 같지만
policy에 따라 실행돼요. (C++17)
d_first + [0, count)가 first + [0, count)와 겹치면 동작은 미정의예요. (C++20)
매개변수
first: 복사할 요소 범위의 시작count: 복사할 요소 수d_first: 대상 범위의 시작policy: 사용할 실행 정책
반환값
위 설명과 같이 대상 범위의 마지막 구성 요소 다음의 반복자.
예외
(2)에서 병렬화에 필요한 임시 메모리가 없으면 std::bad_alloc이 던져져요.
예제
#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
#include <tuple>
#include <vector>
int main()
{
std::vector<std::string> v = {"This", "is", "an", "example"};
std::string* p;
std::size_t sz;
std::tie(p, sz) = std::get_temporary_buffer<std::string>(v.size());
sz = std::min(sz, v.size());
std::uninitialized_copy_n(v.begin(), sz, p);
for (std::string* i = p; i != p + sz; ++i)
{
std::cout << *i << ' ';
i->~basic_string<char>();
}
std::cout << '\n';
std::return_temporary_buffer(p);
}
가능한 출력:
This is an example