为什么函数对象应该按值传递 [英] why function objects should be pass-by-value

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

问题描述

我刚读过经典书Effective C ++,3rd Edition,在第20题中,作者认为内置类型,STL迭代器和函数对象类型更适合于传递值。我可以很好地理解内置和迭代器类型的原因,但 为什么函数对象应该是传值的 ,因为我们知道它是类类型?

解决方案

在一个典型的情况下,一个函数对象很少或者在这种情况下,传递值可能不需要实际传递任何东西 - 传递的值基本上很少或只是一个占位符this is the object。



给定许多函数对象中的少量代码,这导致进一步优化:编译器通常很容易扩展函数对象的内联代码,所以没有参数传递,没有函数

当你传递一个指针或引用时,编译器可以做同样的事情,但它不是完全相同的很容易 - 更常见的是,你将最终创建一个对象,其地址传递,然后通过该指针调用该对象的函数调用操作符。



编辑:这也许值得一提的是,同样适用于lambdas,因为它们只是伪装的函数对象。你不知道类的名称,但是他们在紧挨着的范围中创建一个类,它重载了函数调用操作符,这是在调用lambda时调用的。 [感谢@Mark Garcia。]


I have just read the classic book "Effective C++, 3rd Edition", and in item 20 the author concludes that built-in types, STL iterators and function object types are more appropriate for pass-by-value. I could well understand the reason for built-in and iterators types, but why should the function object be pass-by-value, as we know it is class-type anyway?

解决方案

In a typical case, a function object will have little or (more often) no persistent state. In such a case, passing by value may no require actually passing anything at all -- the "value" that's passed is basically little or nothing more than a placeholder for "this is the object".

Given the small amount of code in many function objects, that leads to a further optimization: it's often fairly easy for the compiler to expand the code for the function object inline, so no parameters get passed, and no function call is involved at all.

A compiler may be able to do the same when you pass a pointer or reference instead, but it's not quite as easy -- a lot more common that you'll end up with an object being created, its address passed, and then the function call operator for that object being invoked via that pointer.

Edit: It's probably also worth mentioning that the same applies to lambdas, since they're really just function objects in disguise. You don't know the name of the class, but they create a class in the immediately surrounding scope that overloads the function call operator, which is what gets invoked when you "call" the lambda. [Thanks @Mark Garcia.]

这篇关于为什么函数对象应该按值传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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