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

Assigns a new target to std::function.

# Declarations

function& operator=( const function& other );

(since C++11)

function& operator=( function&& other );

(since C++11)

function& operator=( std::nullptr_t ) noexcept;

(since C++11)

template< class F >
function& operator=( F&& f );

(since C++11)

template< class F >
function& operator=( std::reference_wrapper<F> f ) noexcept;

(since C++11)

# Parameters

# Return value

*this

# Notes

Even before allocator support was removed from std::function in C++17, these assignment operators use the default allocator rather than the allocator of *this or the allocator of other (see LWG issue 2386).

# Example

#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);
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 2132C++11the overload (4) taking a Callable object might be ambiguousconstrained
LWG 2401C++11assignment operator (3) from std::nullptr_t not required to be noexceptrequired

# See also