std::move() 算法
- 自 C++20 起
- 自 C++17 起
- 自 C++11 起
// (1)
template< class InputIt, class OutputIt >
constexpr OutputIt move( InputIt first, InputIt last, OutputIt d_first );
// (2)
template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 >
ForwardIt2 move( ExecutionPolicy&& policy,
ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first );
// (1)
template< class InputIt, class OutputIt >
OutputIt move( InputIt first, InputIt last, OutputIt d_first );
// (2)
template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 >
ForwardIt2 move( ExecutionPolicy&& policy,
ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first );
// (1)
template< class InputIt, class OutputIt >
OutputIt move( InputIt first, InputIt last, OutputIt d_first );
-
(1) 将范围 [
first
;last
) 中的元素移动到另一个以d_first
开头的范围,从first
开始,一直到last - 1
。警告此操作后,被移动的范围中的元素仍将包含相应类型的有效值,但不一定与移动之前的值相同。
-
(2) 与 (1) 相同,但根据
policy
执行。
这些重载只有在 std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>
(直到 C++20) std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>
(自 C++20 起) 为 true
时才参与重载决议。
参数
first last | 要移动的元素范围。 |
d_first | 目标范围的开头。 未定义行为 如果 |
policy | 要使用的执行策略。有关详细信息,请参阅执行策略。 |
类型要求
InputIt | LegacyInputIterator |
OutputIt | LegacyOutputIterator |
ForwardIt1 ForwardIt2 | LegacyForwardIterator |
返回值
指向最后一个被移动元素之后的元素的输出迭代器 (d_first + (last - first)
)。
复杂度
恰好 last - first
次赋值。
异常
带有模板参数 ExecutionPolicy
的重载报告错误如下
- 如果作为算法一部分调用的函数执行时抛出异常,并且
ExecutionPolicy
是标准策略之一,则调用std::terminate
。对于其他ExecutionPolicy
,行为是实现定义的. - 如果算法未能分配内存,则抛出
std::bad_alloc
。
可能的实现
move (1)
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