Reputation: 458
I have a program that uses Javascript as a scripting language binding to a larger C++ application. I use V8 and webkit interchangeably, but the underlying runtime shouldn't matter for this question.
In this application, I have dynamically created objects will receive callbacks. I'll create this callback binding like this...
function f() {
var obj = CreateNewCallbackObj();
obj.onCallback = dowork; // dowork is a function
}
Clearly this will have GC problems because obj has gone out of scope and will be deleted eventually.
What I want is for the object to self manage its lifetime. The object will eventually receive a callback that will signal the end of its life, and when that happens it can delete itself.
One thought is to self-reference by adding an obj.myself=obj. This seems like the wrong way to do it, but it might work unless a garbage collection algorithm is smart.
Is there a right way to do this? There is no underlying persistant DOM that is built to store objects in, all of the JS objects are allocated dynamically as needed but need some way to stick around within the JS engine.
Upvotes: 7
Views: 1512
Reputation:
Self-references will not guarantee that anything stays alive. In fact, there's about no self-respecting implementation of a GC'd language (that I'm aware of) that uses refcounting alone. Don't even think of abusing the GC algorithm, or any other implementation-defined detail - that way lies madness.
As for alternatives: Create some always reachable (e.g. global) object which holds all these objects (and thus keeps them alive) and provide a method to remove an object. Then pray nobody else got a reference - or even better, don't worry about this. The whole point of GC is that you shouldn't (have to) know/care when memory is released.
You could also add an alive
property, check that at the start of all methods and raise an error if a method is invoked when !this.alive
- that's no guarantee, of course, but it may help debugging.
Upvotes: 7