Problem: Using the Last of Something
Sometimes, your C++ program has data objects that are too big to copy efficiently. You can use multiple pointers to refer to one copy of the big data structure to provide some flexibility when this is the case. In a similar situation, your program has multiple pointers to a specific resource or bit of information that you can't copy because it absolutely must be the only copy in the system. This may be the case when there's a central constant or central object that every other part of the system should refer to.
The system can delete the item and release the resources only when the last pointer is done using it. How do you know, however, when there are no more active pointers to the resource or structure? Following are three ways to try to find out.
First try: Passing objects with pointers
Passing objects as parameters to functions is common in object-oriented C++ programs. Pointers usually accomplish this task. Without care, however, the situations shown in Figure 22-1 can occur:

Figure 22-1: What can go wrong with pointers to shared objects.
- One client of an object deletes the shared object out from under another reference.
- All the clients stop using the shared object, but none of them bothers to delete it — thereby leaving it to waste memory.
Second try: Passing objects by copying
You can solve this problem by avoiding pointers and passing ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access