public member function
<functional>

std::function::operator=

copy (1)
function& operator= (const function& rhs);
move (2)
function& operator= (function&& rhs);
target (3)
template <class Fn> function& operator= (Fn&& fn);
template <class Fn> function& operator= (reference_wrapper<Fn> fn) noexcept;
clear (4)
function& operator= (nullptr_t fn);
Assign function object
Assigns a new value to the function object, replacing its current target:

(1) copy assignment
The object copies the target of rhs.
(2) move assignment
The object acquires the target of rhs.
rhs is left in an unspecified but valid state.
(3) target assignment
The object copies fn as its target.
(4) clearing assignment
The object becomes an empty function object.

Parameters

rhs
A function object of the same type (with the same signature, as described by its template parameters) whose target is either copied or moved.
If rhs is an empty function object, the object becomes an empty function.
fn
Either a function, a function pointer, a pointer to member, or any kind of function object (i.e., an object whose class defines operator(), including closures and other instantiations of function).
If fn is a null pointer, a null member pointer or an empty function object, the object becomes an empty function.
Otherwise, the object is set to target a decayed copy of fn (internally initialized with std::move(fn)).

Return value

*this

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// function::operator= example
#include <iostream>     // std::cout
#include <functional>   // std::function, std::negate

int main () {
  std::function<int(int)> foo,bar;
  foo = std::negate<int>();                              // target
  bar = foo;                                             // copy
  foo = std::function<int(int)>([](int x){return x+1;}); // move
  bar = nullptr;                                         // clear

  std::cout << "foo: " << foo(100) << '\n';

  return 0;
}


Output:
foo: 101

Data races

Both the object and its target are modified.
The move-assignment (2) modifies rhs.

Exception safety

If the assigned target is either a function pointer or a reference_wrapper, it never throws exceptions (no-throw guarantee).
Otherwise, it can throw if the assignment of the target callable object throws.

See also