Solution: Releasing Resources with the Counted Pointer Idiom

The Counted Pointer idiom addresses the forces that I mention in the preceding section and helps you solve the problem of memory management with dynamically allocated objects. The solution involves making only a small addition to the object being shared and adding another class.

Two classes are involved in the solution:

  • Body: The body is the object that will be referenced and shared; it probably exists already. A reference counter in the body keeps track of the number of pointers to it by other objects.
  • Handle: The handle is introduced as the only class in the system that's allowed to have a reference directly to the body.

All references to the body are made through the handle. Accesses to the body through the handle manipulate the reference counter, incrementing it when a new class points to the handle and decrementing it when a reference to the handle is eliminated. Figure 22-2 shows the structure of the solution.

images

Figure 22-2: A class diagram of Counted Pointer.

The handle objects are passed by value throughout the system, which causes them to be allocated and destroyed automatically. If the reference count was stored in the handle, it would be copied, which would result in handles racing to delete or preserve the body. The actual reference count is stored in the body to prevent this problem with the counter being ...

Get Pattern-Oriented Software Architecture For Dummies now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.