Consider the following simple C++ code with normal pointers.
Using smart pointers, we can make pointers to work in way that we don’t need to explicitly call delete. Smart pointer is a wrapper class over a pointer with operator like * and -> overloaded. The objects of smart pointer class look like pointer, but can do many things that a normal pointer can’t like automatic destruction (yes, we don’t have to explicitly use delete), reference counting and more.
The idea is to make a class with a pointer, destructor and overloaded operators like * and ->. Since destructor is automatically called when an object goes out of scope, the dynamically allocated memory would automatically deleted (or reference count can be decremented). Consider the following simple smartPtr class.
Can we write one smart pointer class that works for all types?
Yes, we can use templates to write a generic smart pointer class. Following C++ code demonstrates the same.
Smart pointers are also useful in management of resources, such as file handles or network sockets.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Applications of Pointers in C/C++
- What are near, far and huge pointers?
- Pointers vs References in C++
- Pointers in C/C++ with Examples
- What are Wild Pointers? How can we avoid?
- The length of a string using pointers
- C++ Program to compare two string using pointers
- Program to reverse an array using pointers
- Why C treats array parameters as pointers?
- Pointers in C and C++ | Set 1 (Introduction, Arithmetic and Array)
- Program to Reverse a String using Pointers
- Dangling, Void , Null and Wild Pointers
- How to implement user defined Shared Pointers in C++
- Computing index using pointers returned by STL functions in C++
- Declare a C/C++ function returning pointer to array of integer pointers
Improved By : BabisSarantoglou