UCSC-CRL-92-27: SMART POINTERS: THEY'RE SMART, BUT THEY'RE NOT POINTERS

06/01/1992 09:00 AM
Computer Science
There are numerous times when a C++ user could benefit from a pointer variant that has more functionality than is provided by the basic, language-defined pointer. For example, type-accurate garbage collection, reference counting, or transparent references to distributed or persistent objects, might be implemented with classes that provide pointer functionality. The C++ language directly supports one kind of pointer substitute, the smart pointer, in the form of overloadable indirection operators: -> and *. In this paper we evaluate how *seamlessly* smart pointers can replace raw pointers. The ideal is for client code not to care whether it is using raw pointers or smart pointers. For example, if a typedef selects whether raw or smart pointers are used throughout the program, changing the value of the typedef should not introduce syntax errors. Unfortunately, C++ does not support pointer substitutes well enough to permit seamless integration. This paper presents the desired behavior of smart pointers in terms of the semantics of raw pointers that the smart pointers try to emulate. Then, we describe several ways of implementing smart pointers. For each, we show cases in which the smart-pointers fail to behave like raw pointers. From among the choices, we explain which is the best for emulating the standard pointer conversions. *Accessors* are similar to smart pointers, but have certain advantages. This paper discusses the differences between accessors and smart pointers, and shows why our conclusions about type conversion behavior also apply to accessors. Whether a programmer prefers smart pointers or accessors, this paper shows the limitations and recommends an implementation.

UCSC-CRL-92-27