C ++ 11:通过引用或值传递(lambda或其他)函数对象? [英] C++11: pass (lambda or other) function object by reference or value?
问题描述
这最初是该问题的一部分:
This was originally part of this question:
Passing lambda declared using auto-keyword by non-const reference as argument to std::function parameter type
,但我决定将其分开。
在什么情况下通过lambda或其他方法更好/更惯用通过引用或值来获取函数对象?
In what circumstances is it better/more idiomatic to pass a lambda or other function object by reference or value?
推荐答案
您对 lambda使用与 any相同的规则作为参数的对象。
You use the same rules for "lambda"s that you would for any object that you take as a parameter.
如果函数的目的是为调用者修改对象,则函数应使用非常量引用。如果该函数只是使用对象而不更改它,则应使用 const&
。如果要将对象复制/移动到其内部存储中,则应该按值传递。
A function should use non-const reference if the intent of the function is to modify the object for the caller. The function should use const&
if it is just using the object without changing it. And it should pass by value if it is going to copy/move the object into its internal storage.
这篇关于C ++ 11:通过引用或值传递(lambda或其他)函数对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!