I am using g++@7.3.0 in ubuntu18.04 in WSL, and I am learning c++ lambda from cpprefernce. And I find some differences between c++11&c++17 of lambda.
std::function<int(void)> f(int i) {
auto y = [=]() { return i; };
return y;
}
int main() {
auto p = f(3);
std::cout << p() << std::endl;
return 0;
}
With c++11, i in f will be captured and pass to p, and when p is called it will return i, so the result is 3. If I use refernce capture:
std::function<int(void)> f(int i) {
auto y = [&]() { return i; };
return y;
}
On my pc I can compile it but the result will not be 3. It's something random.That's fine because it's a UB according to cppreference. But when I turn to c++14, like:
auto f(int i) {
auto y = [&]() { return i; };
return y;
}
The result is 3. Why? Is this 3 the same one of i in f? The lifetime of i exsits with p? Or it's still an UB, but g++ make it like this?
Aucun commentaire:
Enregistrer un commentaire