y recent C++ 10-Minute Solution titled "Using a Good Parasite Class to Design a Self-Clearing Memory Buffer" was greeted with skepticism, raised eyebrows, and a torrent of questions from readers who were puzzled by the notion of objects that are never destroyed—seemingly a violation of the C++ object model.
Readers have also wondered what other advantages a good parasite class might offer and whether they can declare additional member functions in such a class. In the following sections, I answer these and many other questions.
Good Parasite Q & A
Q. What Exactly Is a "Good Parasite" Class?
A.Unlike ordinary C++ classes, the good parasite has unique design requirements. Here's the recipe for a good parasite class:
- You declare the destructor, assignment operator, copy constructor, and new operator private and delete them.
- You can instantiate a good parasite object only using placement new; all other conventional methods of instantiation, such as allocating the object on the stack, defining a static object, and so on, are disabled.
- A good parasite cannot have any data members, nor can it declare virtual member functions. This restriction guarantees that a good parasite object will have a practically zero-memory footprint.
- The constructor performs the operation that the good parasite should apply to the buffer on which it's allocated. You can declare additional member functions as long as they comply with certain restrictions (explained below).
- A good parasite object lives on a dual-purpose memory buffer. In the example from the 10-Minute Solution, the raw buffer serves both as the substratum of the Zeroer object and as the SMS record itself. In other words, unlike conventional placement new usage, you're not dealing with a raw memory buffer that was allocated for the sole purpose of hosting another object. Instead, the good parasite is closer to a union that has two members coexisting on the same memory address.
- Every time you want to invoke the operation that the good parasite represents, you construct a new object on the same memory address.
- Good parasites are never destroyed.
Q. Why Use the Good Parasite Idiom Over Other Techniques for Solving the Self-Recycling Buffer Problem?
A.You don't really have to use the good parasite class for implementing a self-recycling buffer. Indeed, there are dozens of ways to implement a self-recycling buffer, some dating back to the early 1970s. Most of these designs rely on orthodox, well-tested, and non-controversial C and C++ concepts.
I used the self-recycling buffer problem as just a pretext for presenting a revolutionary and controversial feature of C++09. I believe that the good parasite can be useful in solving other programming problems, such as traversing the records of a database table, representing a media player's playlist, or anywhere you need a fixed-sized memory buffer.