std::function<R(Args...)>::operator=
来自cppreference.com
< cpp | utility | functional | function
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 对于实参类型
Args...
和返回类型 R
可调用 (Callable) 。5) 设置 *this 的目标为 f 的副本,如同以执行 function(f).swap(*this);
目录 |
[编辑] 参数
other | - | 要复制其目标的另一 std::function 对象
|
f | - | 用以初始化目标的可调用物 |
类型要求 | ||
-F 必须满足可调用 (Callable) 。
|
[编辑] 返回值
*this
[编辑] 注解
即便在 C++17 中从 std::function
移除分配器支持之前,这些赋值运算符使用的也是默认分配器,而不是 *this 或 other 的分配器(见 LWG 问题 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 移除) |
赋值新的目标 (公开成员函数) |