How to capture this
only weakly in a anonymous function?
I couldn't find anything in the docs regarding whether (or how) the variables captured by a anonymous function / lambda expression could be tweaked. The problem is that these functions seem to capture all variables from the stack frame, they are created in, at least by default. Particularly, they always capture this
, which is problematic when using them for signal handlers, because the handlers turn into hard references to this
then, probably causing reference cycles.
Does Vala have some mechanism on how to prevent lambdas from capturing hard references of this
? Currently, I'm creating a new class for each signal handler, like A.Handler
, where I only keep a weak reference to the actual this
of A
which I need to reference from inside the handler, but I think this undermines the benefits of lambda expressions.
Inside a lambda, no. The standard approach is this:
class Foo : Whatever {
public Foo {
unowned Foo unowned_this = this;
this.bar_signal.connect(unowned_this.bar_handler);
}
private void bar_handler() {
...
}
}
This doesn't capture a reference to this, but you also cannot capture any other variables.
来源:https://stackoverflow.com/questions/39014695/how-to-tweak-the-variables-which-a-lambda-expression-in-vala-captures