我遇到了this问题,其中answer描述了有关如何使用通用lambda函数替换 std::function
technique以及如何重新连接停止条件以启用返回类型推断的详细信息。
基于上述内容,我创建了以下工作示例:
#include <cstdio>
void printSeq(unsigned start) {
auto recursion = [](auto&& self, const char* format, unsigned current) {
printf(format, current);
if(!current)
return static_cast<void>(printf("\n"));
else
self(self, ", %u", current - 1);
};
recursion(recursion, "%u", start);
}
int main() {
return (printSeq(15), 0);
}
我的问题是,在这种情况下,使用
auto&&
而不是auto&
有什么优势?我应该在这里使用std::move
吗? 最佳答案
auto&
仅是左值。
直到您重构并用临时代理备注器替换左值递归对象为止,这无关紧要。auto&&
是无害的,表示“我不介意这是临时性的还是什么,只是不复制”,在这里表达得很好。 auto&
指出“不允许使用临时人员!”有时您在引用时要排除临时对象,但这很少见。auto const&
,auto
和auto&&
应该是您的面包和黄油。
仅当您的操作明确地与编写有关并且可以接受代理引用时,才使用auto&
。