命名空间
变体
操作

std::move

来自 cppreference.cn
< cpp‎ | 算法
 
 
算法库
有约束算法与针对范围的算法 (C++20)
有约束的算法,例如 ranges::copyranges::sort 等……
执行策略 (C++17)
排序及相关操作
划分操作
排序操作
二分搜索操作
(于已划分范围上)
集合操作(于已排序范围上)
归并操作(于已排序范围上)
堆操作
最小/最大值操作
(C++11)
(C++17)
字典序比较操作
排列操作
C 库
数值操作
未初始化内存上的操作
 
定义于头文件 <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) 将范围 [firstlast) 中的元素移动到从 d_first 开始的另一个范围,从 first 开始并进行到 last。此操作后,被移动的范围中的元素仍将包含适当类型的有效值,但不一定是移动之前的值。
2)(1),但根据 policy 执行。
仅当满足以下所有条件时,此重载才参与重载决议

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

(C++20 前)

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

(C++20 起)

如果 d_first 在范围 [firstlast) 内,则行为是未定义的。在这种情况下,可以改用 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)
将参数转换为亡值
(函数模板) [编辑]
将一个范围的元素移动到一个新位置
(算法函数对象)[编辑]