Namespaces
Variants

std::function<R(Args...)>:: operator=

From cppreference.net
Utilities library
Function objects
Function invocation
(C++17) (C++23)
Identity function object
(C++20)
Old binders and adaptors
( until C++17* )
( until C++17* )
( until C++17* )
( until C++17* )
( until C++17* ) ( until C++17* ) ( until C++17* ) ( until C++17* )
( until C++20* )
( until C++20* )
( until C++17* ) ( until C++17* )
( until C++17* ) ( until C++17* )

( until C++17* )
( until C++17* ) ( until C++17* ) ( until C++17* ) ( until C++17* )
( until C++20* )
( until C++20* )
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 target のコピーを、以下のように実行して割り当てる: function ( other ) . swap ( * this ) ;
2) other ターゲット * this に移動する。 other は有効な状態であるが値は未指定となる。
3) 現在の target を破棄します。 * this はこの呼び出し後に empty になります。
4) * this target を呼び出し可能オブジェクト f に設定する。これは function ( std:: forward < F > ( f ) ) . swap ( * this ) ; を実行するのと同等である。この演算子は、 f が引数型 Args... と戻り値型 R に対して Callable でない限り、オーバーロード解決に参加しない。
5) target * this のコピーとして設定します。これは function ( f ) . swap ( * this ) ; を実行した場合と同様です。

目次

パラメータ

other - 別の 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; // オーバーロード (1)
    assert(f1 != nullptr and f1(1) == 2);
    f1 = std::move(f2); // オーバーロード (2)
    assert(f1 != nullptr and f1(1) == 2);
    // f2 は有効だが未規定の状態
    f1 = nullptr; // オーバーロード (3)
    assert(f1 == nullptr);
    f1 = inc; // オーバーロード (4)
    assert(f1 != nullptr and f1(1) == 2);
    f1 = [](int n) { return n + n; }; // オーバーロード (4)
    assert(f1 != nullptr and f1(2) == 4);
    std::reference_wrapper<int(int)> ref1 = std::ref(inc);
    f1 = ref1; // オーバーロード (5)
    assert(f1 != nullptr and f1(1) == 2);
}

欠陥報告

以下の動作変更に関する欠陥報告書は、以前に公開されたC++規格に対して遡及的に適用されました。

DR 適用対象 公開時の動作 正しい動作
LWG 2132 C++11 Callable オブジェクトを受け取るオーバーロード ( 4 ) が曖昧になる可能性がある 制約付き
LWG 2401 C++11 std::nullptr_t からの代入演算子 ( 3 ) がnoexceptであることが要求されていない 要求される

関連項目

ターゲットを置換または破棄する
( std::move_only_function の公開メンバ関数)
(C++17で削除)
新しいターゲットを割り当てる
(公開メンバ関数)