这个问题刚刚出现在我的脑海里,我真的不知道怎么弄明白。
让我告诉你我的意思:
int x = 1;
auto lambda1 = [x](){
// do something with x, not specified here though
}
auto lambda2 = [](int x){
// do something with x, not specified here though
}
lambda1();
lambda2(x);
假设我们在给定时间只有 lambda1 或 lambda2。
在那种情况下哪个函数会更快?我很确定差异很小,即使有任何差异,但这引起了我的兴趣,我真的很想知道!
问我们是否只使用一个 int 可能是非常愚蠢的,但在更大范围的 lambda 中可能存在可测量的差异。
最佳答案
第一个翻译成
struct _ {
int x;
_(int x_): x(x_) {}
void operator()() const {...}
};
第二个翻译成
struct _ {
_() = default;
void operator()(int x) const {...}
};
前者可能对关闭施工现场产生各种影响*,后者可能对关闭调用现场产生完全相同的影响*。
* - 取决于
关于c++ - 使用 Lambdas 时,通过捕获子句按值传递还是通过作为参数传递更高效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35060939/