首页 > 解决方案 > Vala 闭包参考循环

问题描述

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

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

    construct {
        this.bind_property("num", this, "result", 0,
            (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 时,绑定才会被移除,但只有在投标及其闭包被移除时,refcount 才会达到 0。

有没有办法让闭包引用this弱?还是在 refcount 达到 1 时进行探测以将其删除?

标签: glibvalagobjectreference-cycle

解决方案


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

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

推荐阅读