Reference Counting and Not Reference Counting

The QueryInterface method might be mildly interesting, but for the most part, it’s transparent in Visual Basic and there’s not much you can do about it. That’s not always the case with reference counting.

COM didn’t invent the concept of reference counting. It’s been around for a long time, and you might even find it handy in your own classes. We’ll use a form of it in the file notification server in Chapter 11.

The idea is that any object that might be referenced by multiple users keeps a count of how many users it has. Whenever a new user connects to the object, the count is incremented. When a user disconnects from the object, the count is decremented. When the count reaches zero, no one is using the object and it can call its Terminate event and deallocate its data. In simple reference counting schemes such as COM’s, it doesn’t matter what the count is, just whether it’s zero. The scheme works if all the participants faithfully do their part to keep the reference count accurate.

COM objects are responsible for keeping a reference count, and Visual Basic, as a good implementor of COM, keeps reference counts religiously—sometimes too religiously. This all happens behind the scenes: you can’t see how it works and you can’t change its behavior through legal means. Of course, hardcore programmers can do anything they want, but let’s take a closer look at the automatic system before attempting to modify it.

COM programmers in C, C++, and B-- don’t have the luxury of ignoring reference counts. In these COM-ignorant languages, any reference counting that gets done must be done by you, the class implementor.