This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <functional> | |
#include <vector> | |
void add_func(std::vector<std::function<int(int)>>& fvec) | |
{ | |
int x = 6; | |
fvec.emplace_back([=](int value) | |
//fvec.emplace_back([&](int value) | |
{ | |
return value % x; | |
}); | |
} | |
int main() | |
{ | |
std::vector<std::function<int(int)>> fvec; | |
add_func(fvec); | |
auto f = fvec.back(); | |
std::cout << f(10) << std::endl; | |
return 0; | |
} |
When line 10 is used instead of line 9, running this code yields 10 instead of 4.
Ideally, 4 should be returned as the remainder of 10 divided by 6. If line 10 is used, however, the lambda function created encloses a reference to the variable x which goes out of scope as soon as the function add_func() completes execution.
After add_func() is called, the lambda function stored inside the vector uses a reference to x which is no longer valid (x only exists while add_func() is being executed). Therefore, the lambda function uses a reference to a variable with undefined value. Calling the lambda function therefore will yield to undefined results.
No comments:
Post a Comment