I've been trying to wrap CPointer types of native objects with the idea that the object controls the lifespan of the underlying native object.
In C++ terms, I would do something like:
class T {
private:
U other;
};
Or even:
class T {
public:
T(){ other = new U; }
~T(){ delete other; }
private:
U other;
};
Which I'm not even sure if would be correct, but the idea is simple: Object "other" is held by the object of type T.
The problem is that I don't know if that is even possible in Kotlin native:
class T {
private val arena = Arena()
private val ptr: Cpointer<U> = arena.alloc()
// Should I delegate the free method to T?
}
As far as I am concerned, the arena will not reclaim the memory automatically, right? I have to call .free()
or .clear()
.
Is there any way to achieve such effect? Or the only way is to use memScoped
and calling arena's clear or ptr free manually?
Alternatively, what are the best approaches to prevent memory waste/leaking in K/N?
Kotlin/Native has no ways to work in a C++ manner as you wish. For now, best practice is still to provide your own dispose()
methods in your class. In my answer, I am referring to this GitHub issue and this conversation in Kotlin's public Slack. I also recommend these resources as preferrable Kotlin/Native-discussing places.