How to capture by reference and avoid moves of the captured variable #1338
Replies: 3 comments 3 replies
-
Does the transpiler really not detect those references? I.e. does it actually break? |
Beta Was this translation helpful? Give feedback.
-
I seem to have luck if I save a pointer using the capture, the syntax1 code attempts to move from it on last use, but it does no harm. example: () = {
vec: std::vector<int> = (1, 2, 3);
lambda := :() = {
v := vec&$;
std::println("{}", v*[1]);
};
lambda();
std::println("vec size: {}", vec.size());
} Becomes auto example() -> void{
std::vector<int> vec {1, 2, 3};
auto lambda {[_0 = (&vec)]() mutable -> void{
auto v {_0};
std::println("{}", CPP2_ASSERT_IN_BOUNDS_LITERAL((*cpp2::impl::assert_not_null(cpp2::move(v))), 1));
}};
cpp2::move(lambda)();
std::println("vec size: {}", CPP2_UFCS(size)(cpp2::move(vec)));
} Ouput: |
Beta Was this translation helpful? Give feedback.
-
So the issue is that the move on last use isn't recognizing that the lambda has a pointer to the vector, and that pointer potentially extends the "definite last use" location of the vector to be the last use of the lambda. That sounds like a bug in the "definite last use" tracker. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
In cpp1, I often create helper lambas that capture local variables by reference, e.g.
I tried to do the same in cpp2:
But then I remembered about move-on-last-use and became scared of this code: something as simple as
words2 := words;
before thefor
loop can break this code becausewords
would be moved.I imagine the wrapper pattern is also affected by this move-on-last-use rule. E.g. cpp1 (full example in cpp2):
So the question is what's the idiomatic way to write such helper functions, wrappers, etc? So far the only two ideas I have are to name such captured variables
guard
or add_ =
at the end of the scope, but both are not ideal.(and I guess the hidden question is if move-on-last-use without escape analysis (which would likely complicate the compiler significantly and reduce the number of moves) is a good idea)
Beta Was this translation helpful? Give feedback.
All reactions