Namespaces
Variants

std::move

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

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


 
헤더에 정의 <algorithm>
template< class InputIt, class OutputIt >
OutputIt move( InputIt first, InputIt last,
               OutputIt d_first );
(1) (C++11부터)
(C++20부터 constexpr)
template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 >
ForwardIt2 move( ExecutionPolicy&& policy,
                 ForwardIt1 first, ForwardIt1 last,
                 ForwardIt2 d_first );
(2) (C++17부터)
1) 범위 내 요소들을 이동합니다. [first, last), 그 대상 범위는 d_first부터 시작하여 last. 이 연산 후, 이동된 범위의 요소는 여전히 적절한 타입의 유효한 값을 포함하지만, 이동 전과 동일한 값일 필요는 없습니다.
2) (1)과 동일하지만, (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가 범위 [first, last) 내에 있으면, 동작은 정의되지 않습니다. 이 경우, std::move_backward를 대신 사용할 수 있습니다.

매개변수

first, last - 소스 범위를 정의하는 반복자 쌍 범위의 요소를 이동합니다.
d_first - 대상 범위의 시작
policy - 사용할 실행 정책
타입 요구 사항
-
InputIt은(는) 다음 요구 사항을 충족해야 합니다: LegacyInputIterator.
-
OutputIt은(는) 다음 요구 사항을 충족해야 합니다: LegacyOutputIterator.
-
ForwardIt1, ForwardIt2은(는) 다음 요구 사항을 충족해야 합니다: LegacyForwardIterator.

반환값

마지막으로 이동된 요소 바로 다음 요소를 가리키는 반복자입니다.

복잡도

정확히 std::distance(first, last) 번의 이동 할당이 수행됩니다.

예외

템플릿 매개변수 이름이 ExecutionPolicy인 오버로드는 다음과 같이 오류를 보고합니다:

  • 알고리즘의 일부로 호출된 함수의 실행이 예외를 던지고 ExecutionPolicy이(가) 표준 정책 중 하나이면, std::terminate이(가) 호출됩니다. 다른 ExecutionPolicy의 경우, 동작은 구현 정의입니다.
  • 알고리즘이 메모리 할당에 실패하면, std::bad_alloc이(가) 던져집니다.

가능한 구현

template<class InputIt, class OutputIt>
OutputIt move(InputIt first, InputIt last, OutputIt d_first)
{
    for (; first != last; ++d_first, ++first)
        *d_first = std::move(*first);
    
    return d_first;
}

참고

겹치는 범위를 이동할 때, std::move는 왼쪽으로 이동할 때 적합하며 (대상 범위의 시작이 소스 범위 밖에 있음), std::move_backward는 오른쪽으로 이동할 때 적합합니다 (대상 범위의 끝이 소스 범위 밖에 있음).

예제

다음 코드는 스레드 객체(자체적으로 복사 불가능)를 한 컨테이너에서 다른 컨테이너로 이동합니다.

#include <algorithm>
#include <chrono>
#include <iostream>
#include <iterator>
#include <list>
#include <thread>
#include <vector>

void f(int n)
{
    std::this_thread::sleep_for(std::chrono::seconds(n));
    std::cout << "thread " << n << " ended" << std::endl;
}

int main()
{
    std::vector<std::jthread> v;
    v.emplace_back(f, 1);
    v.emplace_back(f, 2);
    v.emplace_back(f, 3);
    std::list<std::jthread> l;
    
    // copy() would not compile, because std::jthread is noncopyable
    std::move(v.begin(), v.end(), std::back_inserter(l));
}

출력:

thread 1 ended
thread 2 ended
thread 3 ended

참고 항목

요소 범위를 역순으로 새 위치로 이동합니다
(함수 템플릿 & 알고리즘 함수 객체)
(C++11)
인수를 xvalue로 변환합니다
(함수 템플릿)
요소 범위를 새 위치로 이동합니다
(알고리즘 함수 객체)