std::move
From 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 から始まる別の範囲に移動します。移動操作の後、移動元の範囲の要素は適切な型の有効な値を保持しますが、移動前の値と同じである必要はありません。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) |
引数をxvalueに変換する (関数テンプレート) |
| (C++20) |
要素の範囲を新しい場所にムーブする (アルゴリズム関数オブジェクト) |