问题描述
在kotlin本机中,有memScoped函数可以在控件超出范围时自动释放分配的内存.是否有类似本地对象的析构函数?
In kotlin native there is memScoped function that automatically free allocated memory when control is going out of scope.Is there something like destructors for local objects?
推荐答案
当内存中不再需要某些对象(Java语言中的finalizer)时,当前的Kotlin/Native不提供用于调用方法的机制,但是内联lambda可以轻松实现实现机制,类似于C ++中的RAII.例如,如果您想确定某些资源始终在离开特定范围后被释放,则可以执行以下操作:
Current Kotlin/Native does not provide mechanism for calling a method when certain object is no longer needed in memory (finalizer in Java speech) but inline lambdas easily allow to implement mechanisms, similar to RAII in C++. For example, if you want to be sure, that some resource is always released after leaving certain scope, you may do:
class Resource {
fun take() = println("took")
fun free() = println("freed")
}
inline fun withResource(resource: Resource, body: () -> Unit) =
try {
resource.take()
body()
} finally {
resource.free()
}
fun main(args: Array<String>) {
withResource(Resource()) {
println("body")
}
}
这篇关于kotlin-native是否具有析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!