简体   繁体   English

在C ++中使用auto声明lambda变量的首选方法是什么?

[英]What is the preferred way to use auto to declare a lambda variable in C++?

Does anyone have any insight into the pros and cons of the various ways to use auto to declare a lambda variable? 有没有人了解使用auto声明lambda变量的各种方式的利弊?
For eg: 例如:

 auto Val = [] { };           // #1
 const auto &LVRef = [] { };  // #2
 auto &&RVRef = [] { };       // #3

Can anyone think of a compelling reason to not always prefer #1? 谁能想到一个令人信服的理由,而不是总是喜欢#1?

I imagine for a template function, the preferred way to declare a callable parameter is to use a universal reference? 我想象对于模板函数,声明可调用参数的首选方法是使用通用引用?

template<class F> void foo(F&& f) { f(); }

Or do most guidelines prefer to declare it as a non-reference parameter? 还是大多数准则更喜欢将其声明为非参考参数?

template<class F> void foo(F f) { f(); }

Thank you! 谢谢!

Can anyone think of a compelling reason to not always prefer #1? 谁能想到一个令人信服的理由,而不是总是喜欢#1?

No. #1 is simpler and there's no performance penalty vs. the other options. 不。#1更简单,与其他选项相比,没有性能损失。

Algorithms taking functors just take them by value normally, but using universal references is reasonable if you want to guarantee no copying the functor for some reason. 带有函子的算法通常只按值取值,但是如果您出于某种原因要保证不复制函子,则使用通用引用是合理的。 If you're writing something that simply forwards the functor then use universal references. 如果您编写的只是转发函子的内容,请使用通用引用。

I'd actually say #2, because I prefer differenting non-mutable and non-reference variables/functor, then declare every other variable const auto& . 我实际上会说#2,因为我更喜欢区分非可变和非引用变量/函数,然后声明所有其他变量const auto& The reason I prefer to also use a reference is that you dont have to care if a function returns a generated value or a reference. 我更喜欢也使用引用的原因是,您不必关心函数是否返回生成的值或引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM