瓦拉封口参考周期

问题描述

我正在用Vala编写一个类,其中我bind将同一对象的两个属性放在一起,并用闭包将一个属性转换为另一个属性

class Foo : Object
{
    public int num { get; set; }
    public int scale = 2;
    public int result { get; set; }

    construct {
        this.bind_property("num",this,"result",(binding,src,ref dst) => {
                var a = src.get_int();
                var b = this.scale;
                var c = a * b;
                dst.set_int(c);
            }
        );
    }
}

闭包保留引用this(因为我使用了this.scale),这创建了一个引用周期,即使所有其他对它的引用都丢失了,它也可以使我的类保持活动状态。

仅当引用计数达到0时,绑定才会被删除,但是只有移除出价及其关闭时,引用计数才达到0。

有没有办法使闭包对this的引用变弱?还是要探查refcount何时达到1才能将其删除

解决方法

未经测试,但是您可以将this分配给弱变量并在闭包中引用它吗?例如:

weak Foo weak_this = this;
this.bind_property(…,(…) => {
    …
    b = weak_this.scale;
    …
}
,

这是Vala编译器的已知缺陷,将在this issue中进行讨论。

目前,可以通过在闭包不捕获this的静态方法中进行绑定来避免此问题。

class Foo : Object
{
    public int num { get; set; }
    public int scale = 2;
    public int result { get; set; }

    construct {
        this.bind_properties(this);
    }

    private static void bind_properties(Foo this_)
    {
        weak Foo weak_this = this_;

        this_.bind_property("num",this_,"result",(binding,src,ref dst) => {
                var a = src.get_int();
                var b = weak_this.scale;
                var c = a * b;
                dst.set_int(c);
            }
        );
    }
}