名稱空間
變體
操作

std::move

來自 cppreference.com
< 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)
將引數轉換為亡值
(函式模板) [編輯]
將一個範圍的元素移動到一個新位置
(演算法函式物件)[編輯]