3 ms·
C++: std::vector<std::function<int(int)>> powers_of_x; for (int i = 0; i < 10; ++1) power_of_x.push_back([=](int x) { return std::pow(x, i); });
by gpderetta 7y ago
C++:
std::vector<std::function<int(int)>> powers_of_x;
for (int i = 0; i < 10; ++1)
power_of_x.push_back([=](int x) { return std::pow(x, i); });
works as one would intuitively expect (a different i is captured for each iteration). The issue is with those languages that conflate values with references.
- masklinn 7y ago… > excluding the special case of low-level languages with capture clauses Of course it works, you're specifically capturing `i` by value. It's not exactly surprising that doing things completely differently yields a different result.
- gpderetta 7y agoTo be fair I missed the note at the end of your commend on my first read. Still, in the specific C++ example, no other capture clause is valid. Also, python could have chosen a slightly different closure semantics and preserved sanity: instead of closing over the binding itself, it could close over each object reference separately (exactly in the same way the default parameter hack works).