std::move
来自 cppreference.cn
定义于头文件 <algorithm> |
||
template< class InputIt, class OutputIt > OutputIt move( InputIt first, InputIt last, |
(1) | (C++11 起) (C++20 起为 constexpr) |
template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 > ForwardIt2 move( ExecutionPolicy&& policy, |
(2) | (C++17 起) |
1) 将范围
[
first,
last)
中的元素移动到从 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 在范围 [
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) |
以逆序将一个范围的元素移动到一个新位置 (函数模板) |
(C++11) |
将参数转换为亡值 (函数模板) |
(C++20) |
将一个范围的元素移动到一个新位置 (算法函数对象) |