14
Oct
2021

Smart Pointers (0/6)

Before talking about smart pointers, I would like to talk briefly about non-smart pointers also known as raw pointers.
If we create a primitive type such as “int” or an object on the heap, the memory responsibilities belong to us. Ignoring the memory control mechanism can cause some problems such as having a dangling pointer, memory leakage, etc…
Memory leakage example with a raw pointer:

 

void foo(int x = 1)
  {
    int *i = new int(10);

    if (x < 2) 
      return;	//memory-leakage	
    
    //some codes
    
    delete i;
}

For the code block above, suppose we have a function named foo taking a parameter and it works when the x value is greater than 2, the function will be broken by the “return” command if the x value is smaller than 2. We have to focus on this possibility! Before checking the x value, an int-type pointer is created named i. If the return command works, who deletes the int *i ? No one! We’ve created a memory leakage. 

Of course, this is a small function, so we can easily recognize the bug! But, it would be hard to recognize memory-leaks on functions with bigger bodies and bigger algorithms. We must avoid memory leakages for our programs.

There are lots of ways to avoid memory leakages but the best way is to use the smart pointers, that’s if we need to use a pointer.

Let’s talk about smart pointers.

Smart pointers are an essential part of C++ since C++98. But the type of std::auto_ptr which comes from C++98 is deprecated.

These include pointers std:unique_ptr, std::shared_ptr and std::weak_ptr.

Smart pointers provide memory management according to the RAII. They include the raw pointer and assume all responsibilities. The smart pointer’s constructor acquires the resource when the object is created and its destructor releases the resource when the object goes out of scope.

In this blog series, we will dive into the standard library’s unique_ptr and shared_ptr. Subsequently, we will write a superficial custom unique pointer and shared pointer to comprehensively understand the standard library’s smart pointer.

Let’s begin with the next article: std::unique_ptr.

Leave a Reply