#include <iostream>
#include <functional>
int main() {
std::vector<int> integers = {0, 1, 2};
std::function<void()> lambda = [integers] {
printf("vector size (in lambda function): %zu\n", integers.size());
};
printf("vector size (in main()): %zu\n", integers.size());
lambda();
return 0;
}
In this simple program, vector integers
is sent into a lambda function by copy, so it is unchanged after this lambda function created.
Now how do I destroy/clear this vector the same moment it sent into this lambda function? Like when a vector is sent into a function by std::move()
?
The closet solution I have so far is to achieve above is:
std::vector<int> integers = {0, 1, 2};
std::function<void()> lambda = [integers] {
printf("vector size (in lambda function): %zu\n", integers.size());
};
integers.clear();
printf("vector size (in main()): %zu\n", integers.size());
lambda();
But even so, the vector is still cleared AFTER lambda function created.
So how do I destroy this vector the moment when lambda function created?
While C++11 only allows references or copied values in lambda captures, C++14 introduces Lambda capture expressions. You can move your vector in one of these expressions.
#include <cstdio>
#include <functional>
#include <utility>
int main() {
std::vector<int> integers = {0, 1, 2};
std::function<void()> lambda = [integers=std::move(integers)] {
// Initializing move ^^^^^^^^^^^^^^^^^^^^
std::printf("vector size (in lambda function): %zu\n", integers.size());
};
std::printf("vector size (in main()): %zu\n", integers.size());
lambda();
return 0;
}
vector size (in main()): 0 vector size (in lambda function): 3