Smart pointers in C++A pointer is used to store the address of another variable. In other words, a pointer extracts the information of a resource that is outside the program (heap memory). We use a copy of the resource, and to make a change, it is done in the copied version. To change the content of the original resource, smart pointers are used. Problems faced with normal pointersBelow is an example that depicts the problem with normal pointers. Created a class Rectangle with two data members (length and breadth). A function fun() dynamically creates an object of Rectangle. When the function fun() ends, the object p gets destroyed. Since we did not delete p, the memory remains allocated, and this allocated resource will not be available to other variables. In the main(), we execute an infinite loop that will keep creating p objects and allocate resources. This problem turns out into a memory leak to which smart pointers is a solution. Code Note - The languages such as JAVA, C# has their garbage collectors that smartly deallocate unused memory resource.Smart pointersWe will implement smart pointers such that they will release the memory of unused resources. Create a class with a pointer, overloaded operators(->, *) and destructors. The destructor will be automatically called when its object goes out of the scope, and automatically the dynamically allocated memory will be deleted. Example Output 100 The above example works only for int. We will create a template that will work for every data type. Code Output 100 Types of smart pointers
This type of object stores only a single object. To assign a different object, current object is deallocated. Code Output 100 100
In shared_ptr, more than one object can point to a single pointer at the same instance of time. A reference counter is maintained for denoting the object using the use_count() method. Code Output 100 100 100 2
Weak_ptr is similar to the shared pointer. The difference is that it does not maintain a reference counter and there is no strong hold of the object on the pointer. This property may result in a deadlock as different objects will try to hold the pointer.
Next TopicTypes of polymorphism in C++
|