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)).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 中已移除) |
賦值一個新的目標 (公共成員函式) |