简体   繁体   中英

How to build a Garbage Collector?

I'm working in Flash, and attempting to use the new "domain memory" available in Flash Player. This essentially lets you work with memory at a low level, but you have to manage the memory yourself, much like C++, which has no built-in garbage collector. I've built a basic allocator/deallocator, but I need some way to build a Garbage Collector or Reference Counter so I can unallocate unused objects. Take the following example:

Rect stageRect = new Rect(0, 0, stage.width, stage.height);
  // syntax is for understanding only
  // actually would allocate memory using my handwritten allocator

I've constructed a new Rect and stored in a class member var. Now lets say I perform some rectangle math on this object, creating 2 more objects.

Rect quarterRect = stageRect.halfWidth().halfHeight();

As you can see, the Rect returned by halfWidth is unused, and can be garbage collected.

The final rect created by halfHeight is stored in the var quarterRect , which I need for later.

How do I detect such unused objects, and dispose of them accordingly? I've been reading up on Reference Counting, Smart Pointers , the GC for C++ , but I still can't figure out how to detect when a reference is unused, to decrement the reference count. Incrementing the ref count is easy : when you set another var to point to this object, ie: a = stageRect , should increase the reference count of stageRect , but how would you know when a is unused? to decrement the reference count? Usually you don't go around setting a = null in modern code. You just expect the platform to detect its an unused ref and dispose it.

Well, let's consider this code:

int someFunction() { // I have no clue about AS3 syntax, but I suppose it's C-like, right?
    Rect a = new Rect(...); // there are no pointers, only references, right?

    // ... some other stuff
} // <- what happens here?

What happens at the closing curly bracket? The a variable goes out of the scope. In C++, when a variable goes out of scope, its destructor is called. What happens in AS3 when the variable goes out of the scope? If nothing happens here, nothing that you can trace programmatically... well, then I am afraid that implementing reference-counting is impossible. For reference-counting, you need a way to tell that a reference to your value has disappeared.

But is AS3 really have no GC? I can't believe in a scripting languages without GC.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM