std:: move
|
定义于头文件
<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 起) |
[
first
,
last
)
中的元素移动到以
d_first
开始的另一范围,从 first 开始直至
last
。此操作后,被移动范围中的元素仍将包含适当类型的有效值,但不一定与移动前的值相同。
|
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() 无法编译,因为 std::jthread 不可复制 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)
|
移动元素范围到新位置
(算法函数对象) |