memory_uninitialized_copy

memory_uninitialized_copy (std::uninitialized_copy)

<memory> 헤더에 정의되어 있어요. 소스 범위 [first, last)의 요소를 d_first에서 시작하는 대상 범위에 복사해 구성해요.

출처: cppreference

본문

template< class InputIt, class NoThrowForwardIt >
NoThrowForwardIt uninitialized_copy( InputIt first, InputIt last, NoThrowForwardIt d_first );  // (1) constexpr since C++26

template< class ExecutionPolicy, class ForwardIt, class NoThrowForwardIt >
NoThrowForwardIt uninitialized_copy( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, NoThrowForwardIt d_first );  // (2) since C++17
  • (1) 소스 범위 [first, last)의 요소를 d_first에서 시작하는 대상 범위에 다음과 같이 구성해요.
for (; first != last; ++d_first, (void) ++first)
    ::new (voidify(*d_first))
        typename std::iterator_traits<NoThrowForwardIt>::value_type(*first);
return d_first;

초기화 중 예외가 발생하면 이미 구성된 객체들이 미지정 순서로 파괴돼요.

  • (2) (1)과 같지만 policy에 따라 실행돼요. (C++17)

d_first + [0, std::distance(first, last))[first, last)와 겹치면 동작은 미정의예요. (C++20)

매개변수

  • first, last: 복사할 요소 범위를 정의하는 반복자 쌍
  • d_first: 대상 범위의 시작
  • policy: 사용할 실행 정책

반환값

대상 범위의 마지막 구성 요소 다음의 반복자.

예제

#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>

int main()
{
    const char* v[] = {"This", "is", "an", "example"};
    auto sz = std::size(v);

    if (void* pbuf = std::aligned_alloc(alignof(std::string), sizeof(std::string) * sz))
    {
        try
        {
            auto first = static_cast<std::string*>(pbuf);
            auto last = std::uninitialized_copy(std::begin(v), std::end(v), first);
            for (auto it = first; it != last; ++it)
                std::cout << *it << '_';
            std::cout << '\n';
            std::destroy(first, last);
        }
        catch (...) {}
        std::free(pbuf);
    }
}

출력:

This_is_an_example_

더 알아보기 (Learn more)

cppreference