In computer science, a smart pointer is an abstract data type that simulates a pointer while providing additional features, such as automatic garbage collection or bounds checking. These additional features are intended to reduce bugs caused by the use of pointers while retaining efficiency. Smart pointers typically keep track of the objects they point to for the purpose of memory management.
The use of pointers is a major source of bugs: the constant allocation, deallocation and referencing that must be performed by a program written using pointers makes it very likely that some memory leaks will occur. Smart pointers try to prevent memory leaks by making the resource deallocation automatic: when the pointer to an object (or the last in a series of pointers) is destroyed, for example because it goes out of scope, the pointed object is destroyed too.
Several types of smart pointers exist. Some work with reference counting, others assigning ownership of the object to a single pointer. If the language supports automatic garbage collection, then this use of a smart pointer is unnecessary.
Smart pointers can facilitate intentional programming by expressing the use of a pointer in the type itself. For example, if a C++ function returns a pointer, there is no way to know if the caller should delete the memory pointed to when the caller is finished with the information.
some_type* ambiguous_function(); // What should be done with the result?
Traditionally, this has been solved with comments, but this can be error-prone. By returning a C++ auto_ptr,
auto_ptr
Handles were a popular solution to memory management in operating systems of the 1980s, such as Mac OS and Windows. Unix file descriptors are essentially handles. Like other desktop environments, the Windows API heavily uses handles to represent objects in the system and to provide a communication pathway between the operating system and user space. For example, a window on the desktop is represented by a handle of type HWND.
Handles have fallen out of favour in recent times, as increases in available memory and improved virtual memory algorithms have made the use of the simpler pointer more attractive.
This article is licensed under the GNU Free Documentation License.
It uses material from the
"Smart pointer".
Home Page • arts • business • computers • games • health • hospitals • home • kids & teens • news • physicians • recreation• reference • regional • science • shopping • society • sports • world