Skip to main content

Smart pointers in C++

Using pointers in a program increases the risk of memory and resource leaks. Programmers have to make sure that they always free memory (acquired by new operator) using delete operator. Bare pointers in C++ are not exception safe , they do not get destroyed (release memory) if there is an exception in your program.

Smart pointers are helpful to avoid all the problems mentioned above. There are many kinds of smart pointers but in this blog post we will discuss 2 types of smart pointers: unique_ptr and shared_ptr.

What are smart pointers ?
Smart pointers are wrapper over a normal C++ pointer. They are objects that store pointer to dynamically allocated objects. They conceptually own the object pointed to, they delete the object as soon as object is no longer required and goes out of scope.

Difference between normal and smart pointer
The main difference between a normal and smart pointer is that normal pointer do not get deleted unless delete operator is called. On other hand smart pointer deletes the object pointed to as soon as the object goes out of the scope.

Let's try to understand this with a simple example.
void testPointers()
{
    ClassToTest *ct=new ClassToTest(); //normal pointer
    std::unique_ptr<ClassToTest> smartCt(new ClassToTest()); //smart pointer
}
//smartCt gets deleted after this block automatically but ct will not (because no delete operator is called on it) and hence cause a memory leak unless

Types of smart pointers

unique_ptr
A unique_ptr does not share its pointer. Means its a single ownership case. It cannot be used in a scenario where copy of a pointer is required. But its ownership can be moved to another unique_ptr but then the original unique_ptr is no longer the owner of that.It cannot be passed as by value in functions.

To create a unique_ptr you have two ways
//first
unique_ptr<ClassToTest> smartCt1(new ClassToTest());
//second way is to use make_unique helper function
unique_ptr<ClassToTest> smartCt2=make_unique<ClassToTest>();
shared_ptr
shared_ptr is a type of smart pointer that is recommended for situations where multiple owners have to manage the lifetime of an object in memory. It is a reference counted mechanism so when a  new shared_ptr is added the reference count is incremented and whenever shared_ptr goes out of scope or it is reset , reference count is decremented. When reference count reaches 0 the memory of object is released.

Like unique_ptr there are two ways to create shared_ptr
//first
shared_ptr<ClassToTest> sharedC1(new ClassToTest());
//second is using helper function make_sharedshared_ptr<ClassToTest> sharedC2=make_shared<ClassToTest>();
You need to include <memory> header file before using shared_ptr and unique_ptr. 

Comments

Popular posts from this blog

Decoding JPEG image file using libavcodec

I got a chance to work on a video encoding application that decodes series of jpeg files and convert them into ogg theora video file. I used the infamous libavcodec library that is used in FFMPEG . I decided to write blog posts explaining how I decode jpeg images and convert them into ogg video file. This is the first part and in this I will explain how to decode jpeg images using libavcodec. To learn how to write decoded images as a ogg video file please read http://random-stuff-mine.blogspot.com/2017/07/encoding-raw-images-to-ogg-theora-video.html Before reading this blog post you must be aware of using and setting up libavcodec. I highly recommend this tutorial to get basics of using libavcodec http://www.ffmpeg.org/doxygen/0.6/api-example_8c-source.html Allocating input format context We will first allocate input format for reading the file. We will use avformat_open_input function that will allocate AVFormatContext structure passed to it , the function detects input typ...

Multithreaded C# TCP server to handle multiple clients

I decided to write a minimal multithreaded TCP based server as a blog post. Following class can serve as a skeleton for any small or large scale multithreaded TCP socket server. It do not contain much error handling , it is only to give an idea that how multithreaded server works and how it can process multiple clients using threading. using System; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using System.Collections.Generic; namespace RandomStuffMine { public class MTServer {     public int Port{get;set;}     public Socket ServerSocket{get;set;}     private List<Client> Clients=new List<Client>();     private bool runServer=true;     public MTServer(int port)     {         Port=port;         ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);     }   ...

CryptographicException: An error occurred while trying to encrypt the provided data. Refer to the inner exception for more information

I created a new Blazor Server app in Visual Studio 2019 and tried to run it. But I was getting this error CryptographicException: An error occurred while trying to encrypt the provided data. Refer to the inner exception for more information. I couldn't find any reason or solution to this problem. I tried creating the project multiple times but same error. I created a new .Net Core Web App and added a new razor component and included that component in a razor page (cshtml file) like this @(await Html.RenderComponentAsync<GeofenceWork>(RenderMode.ServerPrerendered)) and <component type="typeof(GeofenceWork)" render-mode="serverprerendered" /> As soon as I navigate to this page that has component added I got the same error: CryptographicException: An error occurred while trying to encrypt the provided data. Refer to the inner exception for more information. This was very frustrating. After hours of trying and searching I figured out the solution.  ...