A technique for implementing so-called smart pointers, which detect dangling references, in C++ is described. Smart pointers are objects of special classes with overloaded operators for dereferencing and structure access; they mimic regular pointers but provide some additional smarts. Typical applications for smart pointers are garbage collection (to retire unused objects) and distributed computing (to access remote objects). The author’s technique marks each object with a unique identifying number and replicates that number in all pointers to the object. When the object is deallocated through one pointer, and the memory location is later accessed through one of the other pointers, the dangling reference has a high likelihood of being detected, since the identifying number stored with the pointer is unlikely to match the number that happens to be at the inspected storage location in the heap (which may be inside the free list or another live object).
The cost of the technique is obvious. Each pointer, and each object, must carry an added integer. More important, the outlined implementation places the object identifiers in a common base class and requires that all classes that aim to benefit from the detection scheme derive from that class. In practice, that requirement is likely to be cumbersome.
The paper gives sufficient detail of the C++ implementation to allow someone skilled in the art of C++ templates and operator overloading to replicate it. The author gives some useful hints on structuring code to facilitate turning the checking on and off when switching between test and release versions. The author suggests that the method can be extended to pointers to constant objects, a common C++ idiom. That is in fact true, but the extension to polymorphic pointers, the cornerstone of virtual dispatch in C++, is known to be much more difficult and far from seamless. Unfortunately, no quantitative measurements of the time and space cost of the scheme are provided.