std::move
提供: cppreference.com
ヘッダ <algorithm> で定義
|
||
(1) | ||
template< class InputIt, class OutputIt > OutputIt move( InputIt first, InputIt last, OutputIt d_first ); |
(C++11以上) (C++20未満) |
|
template< class InputIt, class OutputIt > constexpr OutputIt move( InputIt first, InputIt last, OutputIt d_first ); |
(C++20以上) | |
template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 > ForwardIt2 move( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first ); |
(2) | (C++17以上) |
1) 範囲
[first, last)
内の要素を、 first から開始して last - 1 まで、 d_first
から始まる別の範囲にムーブします。 この操作の後、ムーブ元範囲内の要素は適切な型の有効な値のままですが、ムーブ前と同じ値であるとは限りません。2) (1) と同じですが、
policy
に従って実行されます。 このオーバーロードは、 std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> が true である場合にのみ、オーバーロード解決に参加します目次 |
[編集] 引数
first, last | - | ムーブする要素の範囲 |
d_first | - | ムーブ先範囲の先頭。 d_first が範囲 [first, last) 内の場合、動作は未定義です。 その場合、 std::move の代わりに std::move_backward を使用できます。
|
policy | - | 使用する実行ポリシー。 詳細は実行ポリシーを参照してください |
型の要件 | ||
-InputIt は LegacyInputIterator の要件を満たさなければなりません。
| ||
-OutputIt は LegacyOutputIterator の要件を満たさなければなりません。
| ||
-ForwardIt1, ForwardIt2 は LegacyForwardIterator の要件を満たさなければなりません。
|
[編集] 戻り値
最後にムーブした要素の次の要素を指す出力イテレータ (d_first + (last - first))。
[編集] 計算量
ちょうど last - first
回のムーブ代入。
[編集] 例外
テンプレート引数 ExecutionPolicy
を持つオーバーロードは以下のようにエラーを報告します。
- アルゴリズムの一部として呼び出された関数の実行が例外を投げ、
ExecutionPolicy
が標準のポリシーのいずれかの場合は、 std::terminate が呼ばれます。 それ以外のあらゆるExecutionPolicy
については、動作は処理系定義です。 - アルゴリズムがメモリの確保に失敗した場合は、 std::bad_alloc が投げられます。
[編集] 実装例
template<class InputIt, class OutputIt> OutputIt move(InputIt first, InputIt last, OutputIt d_first) { while (first != last) { *d_first++ = std::move(*first++); } return d_first; } |
[編集] ノート
オーバーラップする範囲をムーブする場合、左にムーブする (ムーブ先範囲の先頭がムーブ元範囲の外側である) ときは std::move
が適切であり、右にムーブする (ムーブ先範囲の終端がムーブ元範囲の外側である) ときは std::move_backward
が適切です。
[編集] 例
以下の例はスレッドオブジェクト (コピー可能でない) をあるコンテナから別のコンテナにムーブします。
Run this code
#include <iostream> #include <vector> #include <list> #include <iterator> #include <thread> #include <chrono> void f(int n) { std::this_thread::sleep_for(std::chrono::seconds(n)); std::cout << "thread " << n << " ended" << '\n'; } int main() { std::vector<std::thread> v; v.emplace_back(f, 1); v.emplace_back(f, 2); v.emplace_back(f, 3); std::list<std::thread> l; // copy() would not compile, because std::thread is noncopyable std::move(v.begin(), v.end(), std::back_inserter(l)); for (auto& t : l) t.join(); }
出力:
thread 1 ended thread 2 ended thread 3 ended
[編集] 関連項目
(C++11) |
指定範囲の要素を後ろからムーブします (関数テンプレート) |
(C++11) |
右辺値参照を取得します (関数テンプレート) |