gpt4 book ai didi

memory-leaks - 使用内联函数创建匿名对象。它是否包含封闭类的泄漏?

转载 作者:行者123 更新时间:2023-12-04 04:07:17 24 4
gpt4 key购买 nike

如您所知,java 中的每个匿名对象都包含对封闭类的隐藏引用。
但是使用 kotling 事情变得更加复杂。

Lambda 是匿名类的另一种表示,但在 kotlin 中它的编译并不简单,因为如果 lambda 没有明确捕获封闭类的引用,那么它将像嵌套而不是内部类(匿名类)一样编译并且不会泄漏.

但是内联函数呢。考虑下面的代码

class A {
fun test(){
val it = withReference {
//todo make sth
}
}

}

inline fun withReference(crossinline action: () -> Unit) = object: Reference {
override fun method1() {
action()
}
override fun method2() {
}
}

interface Reference {
fun method1()
fun method2()
}

据我所知,内联函数会像非包装代码一样编译到 A 类,所以问题是开放的。

是否匿名 object: Reference包含指向封闭类的链接 A ,这可能导致内存泄漏?

PS:我已阅读 this article ,但它不包含我的案例的答案

最佳答案

我用的是IntelliJ的反编译器,没有引用外层A

public final class A$test$$inlined$withReference$1 implements Reference {
public void method1() {
}

public void method2() {
}
}

如果 lambda 引用来自外部类 A 的变量,如下所示:
class A {
val valFromA = 10;
fun test(){
val it = withReference {
println("use $valFromA")
}
}
}

然后反编译器显示对 A 对象的引用:
public final class A$test$$inlined$withReference$1 implements Reference {
// $FF: synthetic field
final A this$0;

public A$test$$inlined$withReference$1(A var1) {
this.this$0 = var1;
}

public void method1() {
String var1 = "use " + this.this$0.getValFromA();
System.out.println(var1);
}

public void method2() {
}
}

关于memory-leaks - 使用内联函数创建匿名对象。它是否包含封闭类的泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49983746/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com