命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | utility‎ | functional‎ | function
 
 
 
函数对象
函数调用
(C++17)(C++23)
恒等函数对象
(C++20)
透明运算符包装器
(C++14)
(C++14)
(C++14)
(C++14)  
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)

旧绑定器和适配器
(直到 C++17*)
(直到 C++17*)
(直到 C++17*)
(直到 C++17*)  
(直到 C++17*)
(until C++17*)(until C++17*)(until C++17*)(until C++17*)
(直到 C++20*)
(直到 C++20*)
(直到 C++17*)(直到 C++17*)
(直到 C++17*)(直到 C++17*)

(直到 C++17*)
(until C++17*)(until C++17*)(until C++17*)(until C++17*)
(直到 C++20*)
(直到 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`的*目标*的副本,如同执行`function(other).swap(*this);`一样。
2) 将`other`的*目标*移动到`*this`。`other`处于有效状态,其值未指定。
3) 丢弃当前*目标*。调用后`*this`为*空*。
4) 将`*this`的*目标*设置为可调用对象`f`,如同执行`function(std::forward(f)).swap(*this);`一样。当`f`对于参数类型`Args...`和返回类型`R`是可调用时,此运算符才参与重载决议。
5) 将`*this`的*目标*设置为`f`的副本,如同执行`function(f).swap(*this);`一样。

目录

[编辑] 参数

其他 - 另一个`std::function`对象,用于复制其目标
f - 一个可调用对象,用于初始化*目标*
类型要求
-
F必须满足可调用的要求。

[编辑] 返回值

*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++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
LWG 2132 C++11 接受可调用对象的重载(4)可能存在歧义 已受约束
LWG 2401 C++11 从`std::nullptr_t`的赋值运算符(3)不要求是 noexcept 需要

[编辑] 参阅

替换或销毁目标
(std::move_only_function 的公共成员函数) [编辑]
(在 C++17 中已移除)
赋值一个新的目标
(公共成员函数) [编辑]