std::function<R(Args...)>::function_C++中文网

function() noexcept;

(1) (C++11 起)

function( std::nullptr_t ) noexcept;

(2) (C++11 起)

function( const function& other );

(3) (C++11 起)
(4)

function( function&& other );

(C++11 起)
(C++20 前)

function( function&& other ) noexcept;

(C++20 起)

template< class F >
function( F f );

(5) (C++11 起)

template< class Alloc >
function( std::allocator_arg_t, const Alloc& alloc ) noexcept;

(6) (C++11 起)
(C++17 中移除)

template< class Alloc >

function( std::allocator_arg_t, const Alloc& alloc,

          std::nullptr_t ) noexcept;

(7) (C++11 起)
(C++17 中移除)

template< class Alloc >

function( std::allocator_arg_t, const Alloc& alloc,

          const function& other );

(8) (C++11 起)
(C++17 中移除)

template< class Alloc >

function( std::allocator_arg_t, const Alloc& alloc,

          function&& other );

(9) (C++11 起)
(C++17 中移除)

template< class F, class Alloc >
function( std::allocator_arg_t, const Alloc& alloc, F f );

(10) (C++11 起)
(C++17 中移除)

从各种资源构造 std::function

1-2) 构造 function

3-4) 复制 (3) 或移动 (4) other目标*this目标。若 other,则调用后 *this 将亦为。对于 (4)other 在调用后处于合法但未指定的状态。

5)std::move(f) 初始化目标。若 f 是空指针或指向成员的空指针,则 *this 在此调用后将为此构造函数不参与重载决议,除非 f 对于参数类型 Args... 和返回类型 R 可调用 (Callable) (C++14 起)

6-10)(1-5) ,除了将 alloc 用于分配任何 function 会用到的内部数据结构的内存。

目标是函数指针或 std::reference_wrapper 时,保证使用小对象优化,即始终直接存储这些目标于 std::function 对象中,不发生动态内存分配。可以构造其他大对象于动态分配的存储中,并由 std::function 对象通过指针访问。

参数

other - 用于初始化 *this 的函数对象
f - 用于初始化 *this 的可调用对象
alloc - 用于内部内存分配的分配器 (Allocator)
类型要求
-F 必须满足可调用 (Callable) 可复制构造 (CopyConstructible) 的要求。
-Alloc 必须满足分配器 (Allocator) 的要求。

异常

注意

std::function 的分配器支持说明贫乏,且实现不一致。一些实现完全不提供重载 (6-10) ,一些提供重载但忽略提供的分配器参数,而一些实现提供重载并将提供的分配器用于构造,但不在重赋值 std::function 时使用。结果, C++17 中移除了分配器支持。

示例