by s9801758 » Jul 2, 2002 @ 3:49pm
"If you create a surface, the ref count is zero. No one uses it."
Theoritically this is incorrect. First of all, objects with a zero-refcount have no right to exist. When you create an object its refcount is one, because the place where you created it has a reference (until it goes out of scope, that is).
"Then if that object is deleted, it will decrease the ref count, and delete the object."
I assume that what you mean is that the sprite will decrease the surface's refcount, and when the surface's refcount equals zero the surface deletes itself.
However, imagine the following case:
Suppose you have a character able to shoot bullets. Obviously all bullets can share the same surface. However, where does the surface exist when no bullets are fired? Since no bullet-sprites exist, no references to the surface exist, and hence the surface will delete itself. This is undesired because you don't want to reload the surface when you shoot a new bullet.
Hence, you have to maintain a persistent reference. The only way you can do this is by a manual AddRef in your client-application.
Hence the client code WILL need to do his own AddRef and Release in some places.
Good hand-written refcounting IS a HARD problem and difficult to maintain. At first reference-counting seems an easy solution to memory-leaks, but in practice it doesn't work that way. It is too easy to lose a reference without releasing it, especially without scoped_references (yuck, another scoped class, please...)
Cheers,
Jape