Home C&C++函数库 c++ 语法 程序源码 Linux C库

std::

function::operator=

公共成员函数  <functional>

copy (1)
function& operator= (const function& rhs);
move (2)
function& operator= (function&& rhs);
target (3)
template <class Fn> function& operator= (Fn&& fn);
template <class Fn> function& operator= (reference_wrapper<Fn> fn) noexcept;
clear (4)
function& operator= (nullptr_t fn);

赋值函数对象
将一个新值赋给函数对象,替换它的当前target:

(1)copy assignment
复制rhs的target对象。

(2) move assignment
获取rhs的target对象。 rhs将处于未指定但有效的状态。

(3) target assignment
该对象存储fn的一个decayed副本作为其target。
  • C++11: 该对象将fn复制为其target。
  • C++14: 该对象将fn复制为其target。如果参数fn不可调用,并且返回作为类模板参数指定的类型,则此函数不参与重载解析。

(4) clearing assignment
对象变成一个空的function对象。


☲  参数


rhs
相同类型的function对象(具有相同的签名,由其模板形参描述),其target用来复制或移动。 如果rhs是一个空函数对象,则该对象将成为一个空函数。

fn
函数、函数指针、成员指针或任何类型的可复制构造函数对象(即类定义operator()的对象,包括closures和函数的其他实例化)。
如果fn是空指针、空成员指针或空函数对象,则该对象初始化为空函数。
否则,对象将初始化为fn的一个decayed副本(使用std::move(fn)进行内部初始化)。

☉  返回值



*this

☣  示例



// function::operator= example
#include <iostream>     // std::cout
#include <functional>   // std::function, std::negate

int main () {
  std::function<int(int)> foo,bar;
  foo = std::negate<int>();                              // target
  bar = foo;                                             // copy
  foo = std::function<int(int)>([](int x){return x+1;}); // move
  bar = nullptr;                                         // clear

  std::cout << "foo: " << foo(100) << '\n';

  return 0;
}

输出:
foo: 101

⇄ 数据竞争



对象及其target都被修改。
move-assignment (2)修改rhs。

☂ 异常安全性



如果分配的target是函数指针或reference_wrapper,它永远不会抛出异常(no-throw保证)。
否则,如果target可调用对象的赋值引发问题,它就会引发。

🍄  另请参阅



function::assign 赋值目标并分配空间(公共成员函数)
function::function 构造函数包装器(公共成员函数)
swap(function) 交换目标(公共成员函数)

联系我们 免责声明 关于CandCplus 网站地图