std::function<R(Args...)>::operator=
来自 cppreference.cn
< cpp | utility | functional | function
function& operator=( const function& other ); |
(1) | (since C++11) |
function& operator=( function&& other ); |
(2) | (since C++11) |
function& operator=( std::nullptr_t ) noexcept; |
(3) | (since C++11) |
template< class F > function& operator=( F&& f ); |
(4) | (since C++11) |
template< class F > function& operator=( std::reference_wrapper<F> f ) noexcept; |
(5) | (since 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); 一样。
内容 |
[edit] 参数
other | - | 另一个 std::function 对象,用于复制其目标 |
f | - | 用于初始化目标的可调用对象 |
类型要求 | ||
-F 必须满足 可调用 (Callable) 的要求。 |
[edit] 返回值
*this
[edit] 注解
即使在 C++17 中从 std::function
中移除分配器支持之前,这些赋值运算符也使用默认分配器,而不是 *this 的分配器或 other 的分配器(参见 LWG issue 2386)。
[edit] 示例
运行此代码
#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); }
[edit] 缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 发布行为 | 正确行为 |
---|---|---|---|
LWG 2132 | C++11 | 接受 可调用 (Callable) 对象的重载 (4) 可能不明确 | 已约束 |
LWG 2401 | C++11 | 来自 std::nullptr_t 的赋值运算符 (3) 不需要为 noexcept |
需要 |
[edit] 参见
替换或销毁目标 ( std::move_only_function 的公共成员函数) | |
(在 C++17 中移除) |
赋予新的目标 (公共成员函数) |