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
- Trie Data Structure using smart pointer and OOP in C++
- Features and Use of Pointers in C/C++
- Applications of Pointers in C/C++
- Pointers in C/C++ with Examples
- Pointers and References in C++
- What are near, far and huge pointers?
- Pointers vs References in C++
- The length of a string using pointers
- What are Wild Pointers? How can we avoid?
- Why C treats array parameters as pointers?
- Difference between Iterators and Pointers in C/C++ with Examples
- C program to sort an array using pointers
- Pointers in C and C++ | Set 1 (Introduction, Arithmetic and Array)
- C++ Program to compare two string using pointers
- Program to reverse an array using pointers
Improved By : BabisSarantoglou