std::move_if_noexcept
From cppreference.com
| ヘッダ <utility> で定義 |
||
template< class T > /* 以下を参照 */ move_if_noexcept( T& x ) noexcept; |
(C++11以降) (C++14以降constexpr) |
|
std::move_if_noexcept は、ムーブコンストラクタが例外を投げない場合、またはコピーコンストラクタが存在しない場合 (ムーブオンリー型の場合) には引数への右辺値参照を取得し、それ以外の場合は引数への左辺値参照を取得します。通常、ムーブセマンティクスと強い例外保証を組み合わせるために使用されます。
std::move_if_noexcept の戻り値の型は、
- std::is_nothrow_move_constructible<T>::value || !std::is_copy_constructible<T>::value が true の場合、T&& です。
- それ以外の場合は、const T& です。
目次 |
[編集] パラメータ
| x | - | 移動またはコピーするオブジェクト |
[編集] 戻り値
例外保証に応じて、std::move(x) または x。
[編集] 計算量
定数。
[編集] 注釈
これは、例えば std::vector::resize で使用されます。これは新しいストレージを割り当て、古いストレージから新しいストレージへ要素をムーブまたはコピーする必要がある場合があります。この操作中に例外が発生した場合、std::vector::resize はそこまでに行ったすべてを元に戻します。これは、ムーブ構築を使用するかコピー構築を使用するかを決定するために std::move_if_noexcept が使用された場合にのみ可能です(コピーコンストラクタが利用できない場合を除く。この場合、ムーブコンストラクタがいずれにせよ使用され、強い例外保証が放棄される可能性があります)。
[編集] 例
このコードを実行
#include <iostream> #include <utility> struct Bad { Bad() {} Bad(Bad&&) // may throw { std::cout << "Throwing move constructor called\n"; } Bad(const Bad&) // may throw as well { std::cout << "Throwing copy constructor called\n"; } }; struct Good { Good() {} Good(Good&&) noexcept // will NOT throw { std::cout << "Non-throwing move constructor called\n"; } Good(const Good&) noexcept // will NOT throw { std::cout << "Non-throwing copy constructor called\n"; } }; int main() { Good g; Bad b; [[maybe_unused]] Good g2 = std::move_if_noexcept(g); [[maybe_unused]] Bad b2 = std::move_if_noexcept(b); }
出力
Non-throwing move constructor called Throwing copy constructor called
[編集] 関連項目
| (C++11) |
関数引数を転送し、型テンプレート引数を使用してその値カテゴリを維持する (関数テンプレート) |
| (C++11) |
引数をxvalueに変換する (関数テンプレート) |