How to tweak the variables, which a Lambda expression in Vala captures?

≡放荡痞女 提交于 2019-12-02 16:51:54

问题


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.


回答1:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!