按值传递函数对象by参考(C ++) [英] Passing functor object by value vs by reference (C++)

查看:109
本文介绍了按值传递函数对象by参考(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比较一般整合函数:

template <class F> double integrate(F integrand);

template <class F> double integrate(F& integrand);

template <class F> double integrate(const F& integrand);

每个的优点和缺点是什么? STL使用第一种方法(pass by value),它是否意味着它是最通用的?

What are the pros and cons of each? STL uses the first approach (pass by value), does it mean it's the most universal one?

推荐答案

小,所以我不认为把它们通过价值会遭受性能的注意(比较它的功能在它的身体的工作)。如果你通过值,你也可以从代码分析中获得,因为一个by值参数是函数的本地,优化器可以告诉何时和何时不从函子的数据成员加载可以省略。

Function objects usually should be small so I don't think that passing them by value will suffer from performance noticably (compare it to the work the function does in its body). If you pass by value, you can also gain from code analysis, because a by value parameter is local to the function and the optimizer may tell when and when not a load from a data member of the functor can be omitted.

如果函子是无状态的,将其作为参数传递意味着没有任何成本 - 函子所用的填充字节不必具有任何特定的值至少使用GCC的Itanium Abi)。

If the functor is stateless, passing it as argument implies no cost at all - the padding byte that the functor takes doesn't have to have any particular value (in the Itanium Abi used by GCC at least). When using references, you always have to pass an address.

最后一个( const T& )缺点是在C ++ 03中不适用于原始函数,因为在C ++ 03中,如果您尝试将 const 应用于函数类型(并且是SFINAE大小写)。更多最近的实现在应用于函数类型时忽略 const

The last one (const T&) has the drawback that in C++03 that doesn't work for raw functions, because in C++03 the program is ill-formed if you try to apply const to a function type (and is an SFINAE case). More recent implementations instead ignore const when applied on function types.

第二个( T& )有一个明显的缺点,你不能传递临时函子。

The second one (T&) has the obvious drawback that you cannot pass temporary functors.

长话短说,除非我在具体案例中看到明显的好处,否则我通常会通过价值。

Long story short, I would generally pass them by value, unless I see a clear benefit in concrete cases.

这篇关于按值传递函数对象by参考(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆