我不明白为什么捕获的值会丢失。我了解它与 LambdaWrapper 对象的超出范围或复制有关。但究竟会发生什么?如果 LambdaWrapper(100) 离开 Add 中的范围并且对 __value 的引用丢失,那么为什么与 LambdaWrapper(300) 不同。
#include <iostream>
#include <vector>
#include <functional>
using namespace std;
class LambdaWrapper {
public:
LambdaWrapper(double new_value): __value (new_value) {
cout << "constructed with " << __value << endl;
__func = [this](){ cout << __value << endl;};
}
void call() const { __func(); }
private:
double __value;
function<void(void)> __func;
};
class LambdaContainer {
public:
void Add(double value) {
LambdaWrapper w(value); //out of scope
parts.push_back(w);
}
void Add(LambdaWrapper w) // passed as value
{
parts.push_back(w);
}
void call() const {
for (const auto& part : parts)
part.call();
}
private:
vector<LambdaWrapper> parts;
};
int main() {
LambdaContainer c;
c.Add(100);
LambdaWrapper w(200);
c.Add(w);
c.Add( LambdaWrapper(300) ); //LambdaWrapper(300) will out of scope too
cout << "==============" << endl;
c.call();
return 0;
}
输出:
constructed with 100 constructed with 200 constructed with 300 ============== 6.95168e-308 <<< WHY? 200 300