Namespaces
Variants

std::uninitialized_copy_n

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

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


 
 
헤더 <memory>
template< class InputIt, class Size, class NoThrowForwardIt >
NoThrowForwardIt uninitialized_copy_n( InputIt first, Size count,
                                       NoThrowForwardIt d_first );
에 정의됨 (1) (C++11부터)
(C++26부터 constexpr)
template< class ExecutionPolicy, class ForwardIt,
          class Size, class NoThrowForwardIt >
NoThrowForwardIt uninitialized_copy_n( ExecutionPolicy&& policy,
                                       ForwardIt first, Size count,
                                       NoThrowForwardIt d_first );
(2) (C++17부터)
1) d_first에서 시작하는 대상 범위에 count에서 시작하는 소스 범위의 처음 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에 따라 실행됩니다.
이 오버로드는 다음 표현식의 값이 true인 경우에만 오버로드 해결에 참여합니다:

std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>

(C++20까지)

std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>

(C++20부터)


만약 d_first + [0, count)이 first + [0, count)과 겹치면 동작이 정의되지 않습니다.

(C++20부터)

매개변수

first - 복사할 요소 범위의 시작
count - 복사할 요소의 개수
d_first - 대상 범위의 시작
policy - 사용할 실행 정책
형식 요구 사항
-
InputIt LegacyInputIterator의 요구 사항을 충족해야 합니다.
-
ForwardIt LegacyForwardIterator의 요구 사항을 충족해야 합니다.
-
NoThrowForwardIt LegacyForwardIterator의 요구 사항을 충족해야 합니다.
-
유효한 NoThrowForwardIt 인스턴스를 통한 증가, 할당, 비교 또는 간접 참조는 예외를 던지지 않아야 합니다.

반환 값

위에서 설명한 대로.

예외

2) 실행 과정 중:
  • 병렬화에 필요한 임시 메모리 자원을 사용할 수 없는 경우, std::bad_alloc이 발생합니다.
  • 알고리즘 인수를 통해 객체에 접근하는 도중 처리되지 않은 예외가 발생하면, 동작은 실행 정책에 따라 결정됩니다 (표준 정책의 경우 std::terminate가 호출됩니다).

참고

기능 테스트 매크로 값 표준 기능
__cpp_lib_raw_memory_algorithms 202411L (C++26) constexpr 에 대한 특수화된 <memory>알고리즘, (1)

가능한 구현

template<class InputIt, class Size, class NoThrowForwardIt>
constexpr NoThrowForwardIt uninitialized_copy_n(InputIt first, Size count,
                                                NoThrowForwardIt d_first)
{
    using T = typename std::iterator_traits<NoThrowForwardIt>::value_type;
    NoThrowForwardIt current = d_first;
    try
    {
        for (; count > 0; ++first, (void) ++current, --count)
            ::new (static_cast<void*>(std::addressof(*current))) T(*first);
    }
    catch (...)
    {
        for (; d_first != current; ++d_first)
            d_first->~T();
        throw;
    }
    return current;
}

예제

#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

결함 보고서

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

DR 적용 대상 발표된 동작 올바른 동작
LWG 2133 C++98 효과 설명은 for 루프와 반복
표현식 ++d_first, ++first, --count을 사용했으며, 이는
인자 종속 조회를 초래하여 operator,
값을 버리며
한 피연산자를
해당 ADL을 비활성화합니다.
LWG 2433 C++11 이 알고리즘은 오버로드된 operator& 가 std::addressof
를 사용하여 가로챌 수 있습니다.

참고 항목

객체 범위를 초기화되지 않은 메모리 영역에 복사합니다
(함수 템플릿)
지정된 개수의 객체를 초기화되지 않은 메모리 영역에 복사합니다
(알고리즘 함수 객체)