Namespaces
Variants

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

来自 zh.cppreference.net
 
 
 
函数对象
函数调用
(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*)
(直到 C++17*)(直到 C++17*)(直到 C++17*)(直到 C++17*)
(直到 C++20*)
(直到 C++20*)
(直到 C++17*)(直到 C++17*)
(直到 C++17*)(直到 C++17*)

(直到 C++17*)
(直到 C++17*)(直到 C++17*)(直到 C++17*)(直到 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>(f)).swap(*this);和返回类型f是可调用对象(Callable)。Args...R
5) 将目标设置为*this的副本,效果如同执行 ffunction(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 中移除)
分配新目标
(公开成员函数)