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++
- Pointers in C/C++ with Examples
- Pointers vs References in C++
- What are near, far and huge pointers?
- What are Wild Pointers? How can we avoid?
- The length of a string using pointers
- Program to Reverse a String using Pointers
- C++ Program to compare two string using pointers
- Why C treats array parameters as pointers?
- Program to reverse an array using pointers
- Pointers in C and C++ | Set 1 (Introduction, Arithmetic and Array)
- Dangling, Void , Null and Wild Pointers
- 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