A smart pointer is an abstract data type that simulates a pointer, providing additional features for accessing objects and managing memory at run-time, for example, automatic destroying of unused objects, throwing of exceptions, inspecting owners, or bounds checking. These additional features are intended to reduce issues caused by the misuse of pointers in the program while retaining efficiency. Smart pointers typically keep track of objects and they help with memory management at run-time.
Using smart pointers helps avoid issues typically caused by the misuse of raw pointers:
The idea of smart pointers consists of matching the lifetime of an object created in dynamic memory with operations between pointers referring to this object. When the object is being created, the smart pointer is also being created for it. When the smart pointer gets an address to another object as a new value, it checks whether the reference exists to the controlled object from the other smart pointers, and destroys the object in the case that nothing refers to it. When the smart pointer is being deleted, but other smart pointers refer to it, the controlled object is not deleted. If the deleted smart pointer is the last reference, the controlled object is deleted together with it. Thus a developer performs only the allocation of an object, while smart pointers control the object in run-time and delete the object when it is not used.
Smart pointers usually work only with classes inherited from a base class that provides support of the pointer features. They are typified for class hierarchy and cannot work with intrinsic data types.
Another reason for implementing smart pointers is its technology for reference counting automatically. This technology matches the number of smart pointers that store the address of the controlled object with the number of references to it, which is being stored in the controlled object. The controlled object must store the counter of references as a positive integer value in itself. When a smart pointer gets the address of the controlled object, the object must increase by one its reference counter. When a smart pointer is delete, set to NULL, or loses the controlled object, the object must decrease by one its reference counter. If a smart pointer gets the reference to a new object when it refers to an existing object, the existing object must decrease its own reference counter and the new object must increase its own reference counter. When the reference counter becomes zero, the controlled object is not used and can be deleted. This implementation provides reliability, usability, performance, and ease of use.
Overview of Classes that Implement Smart Pointers
Copyright © 2002 – 2020. Open Design Alliance. All rights reserved.
|