Parasite's Strange but Useful Behavior
A good parasite class like Zeroer almost looks like a bug. Its peculiar design and usage protocol stands out in several aspects:
- It has no memory footprint at all because it lives at the same address as the buffer (technically, sizeof(Zeroer<512> isn't zero but the buffer and Zeroer overlap).
- You can instantiate Zeroer only by using placement new.
- Zeroer objects are never destructed.
- The information that Zeroer needs is welded into the class itself: its this pointer is equivalent to buffer's address, and the non-type template argument N is the buffer's size.
It may be unusual, but it works. In fact, the good parasite class idiom presented here has plenty of potential applications. Take for example a relational database query that opens a cursor and scrolls down the records that fit the query. You can represent the record key as a template non-type argument. The current record will be represented as a raw memory buffer. The good parasite's constructor will fetch the next record and store it in the buffer when the user hits Next.
Take another example: a media player that displays a variety of fixed-length video clips, where each clip is written to the same recycled buffer before it's displayed. Admittedly, there are other, more traditional ways to accomplish these tasks but the good parasite idiom can be another useful technique you may consider instead of automatically representing everything as vectors.
|Author's Note: Click here for answers to frequently asked questions about the good parasite class.