Types of Smart Pointers

C++ libraries provide implementations of smart pointers in the following types:

  • auto_ptr
  • unique_ptr
  • shared_ptr
  • weak_ptr

Smart Pointers in C++

Prerequisite: Pointers in C++

Pointers are used for accessing the resources which are external to the program – like heap memory. So, for accessing the heap memory (if anything is created inside heap memory), pointers are used. When accessing any external resource we just use a copy of the resource. If we make any changes to it, we just change it in the copied version. But, if we use a pointer to the resource, we’ll be able to change the original resource.

Similar Reads

Problems with Normal Pointers

Some Issues with normal pointers in C++ are as follows:...

Smart Pointers

...

Types of Smart Pointers

As we’ve known unconsciously not deallocating a pointer causes a memory leak that may lead to a crash of the program. Languages Java, C# has Garbage Collection Mechanisms to smartly deallocate unused memory to be used again. The programmer doesn’t have to worry about any memory leaks. C++ comes up with its own mechanism that’s Smart Pointer. When the object is destroyed it frees the memory as well. So, we don’t need to delete it as Smart Pointer will handle it....

auto_ptr

...

unique_ptr

...

shared_ptr

C++ libraries provide implementations of smart pointers in the following types:...

weak_ptr

Using auto_ptr, you can manage objects obtained from new expressions and delete them when auto_ptr itself is destroyed. When an object is described through auto_ptr it stores a pointer to a single allocated object....