std::move
來自 cppreference.com
定義於標頭檔案 <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) |
將一個範圍的元素移動到一個新位置 (演算法函式物件) |