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 目标 设置为可调用对象 f ,如同执行 function ( std:: forward < F > ( f ) ) . swap ( * this ) ; 。此运算符不参与重载决议,除非 f 对参数类型 Args... 和返回类型 R 满足 Callable 要求。
5) * this 目标 设置为 f 的副本,如同执行 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++标准。

缺陷报告 适用标准 发布时行为 正确行为
LWG 2132 C++11 接受 Callable 对象的重载 ( 4 ) 可能存在歧义 添加约束
LWG 2401 C++11 来自 std::nullptr_t 的赋值运算符 ( 3 ) 未要求为noexcept 必须要求

参见

替换或销毁目标对象
( std::move_only_function 的公开成员函数)
(C++17 中移除)
分配新目标
(公开成员函数)