std::function<R(Args...)>::operator=
From cppreference.com
< cpp | utility | functional | function
| function& operator=( const function& other ); |
(1) | (C++11以降) |
| function& operator=( function&& other ); |
(2) | (C++11以降) |
function& operator=( std::nullptr_t ) noexcept; |
(3) | (C++11以降) |
template< class F > function& operator=( F&& f ); |
(4) | (C++11以降) |
| template< class F > function& operator=( std::reference_wrapper<F> f ) noexcept; |
(5) | (C++11以降) |
std::functionに新しいターゲットを代入します。
1) ターゲットを
otherのターゲットのコピーとして代入します。あたかもfunction(other).swap(*this);を実行したかのように動作します。2)
otherのターゲットを*thisに移動します。otherは有効な状態であり、未指定の値になります。3) 現在のターゲットを破棄します。呼び出し後、
*thisは空になります。4)
*thisのターゲットを、あたかもfunction(std::forward<F>(f)).swap(*this);を実行したかのように、呼び出し可能なオブジェクトfに設定します。この演算子は、fが引数型Args...および戻り値型Rに対してCallableである場合を除き、オーバーロード解決に参加しません。5)
*thisのターゲットをfのコピーとして設定します。あたかもfunction(f).swap(*this);を実行したかのように動作します。目次 |
[編集] パラメータ
| その他 | - | ターゲットをコピーする別のstd::functionオブジェクト |
| f | - | ターゲットを初期化するための呼び出し可能なオブジェクト |
| 型要件 | ||
-FはCallableの要件を満たす必要があります。 | ||
[編集] 戻り値
*this
[編集] 注記
C++17でstd::functionからアロケータサポートが削除される前でさえ、これらの代入演算子は、*thisのアロケータやotherのアロケータではなく、デフォルトアロケータを使用します(LWG issue 2386を参照)。
[編集] 例
このコードを実行
#include <cassert> #include <functional> #include <utility> int inc(int n) { return n + 1; } int main() { std::function<int(int)> f1; std::function<int(int)> f2(inc); assert(f1 == nullptr and f2 != nullptr); f1 = f2; // overload (1) assert(f1 != nullptr and f1(1) == 2); f1 = std::move(f2); // overload (2) assert(f1 != nullptr and f1(1) == 2); // f2 is in valid but unspecified state f1 = nullptr; // overload (3) assert(f1 == nullptr); f1 = inc; // overload (4) assert(f1 != nullptr and f1(1) == 2); f1 = [](int n) { return n + n; }; // overload (4) assert(f1 != nullptr and f1(2) == 4); std::reference_wrapper<int(int)> ref1 = std::ref(inc); f1 = ref1; // overload (5) assert(f1 != nullptr and f1(1) == 2); }
[編集] 不具合報告
以下の動作変更を伴う欠陥報告が、以前に公開されたC++標準に遡って適用されました。
| DR | 適用対象 | 公開された動作 | 正しい動作 |
|---|---|---|---|
| LWG 2132 | C++11 | 呼び出し可能なオブジェクトを受け取るオーバーロード(4)が曖昧になる可能性があります。 | 制約付き |
| LWG 2401 | C++11 | std::nullptr_tからの代入演算子(3)はnoexceptである必要はありません。 |
必要 |
[編集] 関連項目
| ターゲットを置き換えるか破棄する ( std::move_only_function の public メンバ関数) | |
| (C++17で削除) |
新しいターゲットを代入する (public member function) |