RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Using a Good Parasite Class to Design a Self-Clearing Memory Buffer : Page 3

Your C++ application doesn't have to allocate a new chunk of memory on every loop iteration. Learn how to implement a single raw memory buffer that knows how to clear itself securely.


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.

Danny Kalev is a certified system analyst and software engineer specializing in C++. He was a member of the C++ standards committee between 1997 and 2000 and has since been involved informally in the C++0x standardization process. He is the author of "The ANSI/ISO Professional C++ Programmer's Handbook" and "The Informit C++ Reference Guide: Techniques, Insight, and Practical Advice on C++."
Email AuthorEmail Author
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date