In this article we will compare C++11 Smart Pointer Implementation shared_ptr and a normal pointer.

Let’s compare shared_ptr and raw pointer based on following aspects i.e.

Missing ++, – – and [] operator

In comparison to a raw pointer, shared_ptr provides only these operators

1.) -> , *
2.)  Comparison Operators

But shared_ptr doesn’t provide,

1.)  Pointer arithmetic like +, -, ++, —
2.)  Operator []

Checkout below example,

Output:

 NULL Check

When we create shared_ptr object without assigning any value then its empty.

Where as, without declaration raw pointer will contain garbage value and we cannot verify if it contains garbage or not 🙂

With shared_ptr user can check for emptiness like this,

We can also access the internal raw pointer from shared_ptr object like this,

Ideally we should not use this because it can cause problem if we delete this pointer by mistake. In that case when shared_ptr object will go out of scope then it will try to delete already deleted memory and it will create our program to crash. We will discuss this in more detail in next post.

Click Here to Subscribe for more Articles / Tutorials like this.