【问题标题】:Redundant constructor overloads in std::function?std::function 中的冗余构造函数重载?
【发布时间】:2016-01-24 14:29:14
【问题描述】:

根据cppreferencestd::function有以下三个构造函数重载:

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

只留下最后一个不就足够了吗?前两个会提供更好的性能吗(无论如何,它们更专业)?如果可以,怎么办?

【问题讨论】:

  • 第三个版本至少得把f作为转发参考。
  • @nwp 同意。但在标准中是这样规定的。一定是有原因的。

标签: c++ constructor language-lawyer c++14 std-function


【解决方案1】:

TLDR:这是一种优化

前两个版本采用std::functions 作为参数,而第三个版本采用任意可调用对象。获取任意可调用对象需要类型擦除,因此在调用 std::function 时最终会产生函数调用开销,并且可能会为创建分配动态内存。

删除前两个重载将使std::function 将另一个std::function 视为通用可调用并类型擦除该函数,因此您最终会得到std::function 调用std::function 调用std::function 和可能每次都支付动态内存分配。

相反,您以不同的方式对待std::function,而不是存储std::function,您只需存储其他std::function 存储的可调用对象,从而降低间接级别和动态内存分配。

【讨论】:

  • @LightnessRacesinOrbit 我认为 nwp 确实得到了一点。如果您对此问题有任何见解,请与我们分享:)
  • @Lingxi:nwp 很准;没有说别的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-21
  • 1970-01-01
  • 1970-01-01
  • 2013-06-14
  • 1970-01-01
相关资源
最近更新 更多