We should create shared_ptr objects carefully.

Checkout below two cases,


1.) Try not to use same raw pointer for creating more than one shared_ptr object because in that case different shared_ptr objects will not get to know that they are sharing the pointer with any other shared_ptr objects.

How this can create problem?

Suppose 2 shared pointers were created with same raw pointer like this,

Suppose when ptr_2 goes out of scope then it will delete associated raw pointer and then ptr_1 will be pointing to a dangling pointer.

So, when ptr_1 goes out of scope then it will again try to delete the associated memory, which is actually a dangling pointer. Hence program will crash.

Check out below example,

 

2.) Don’t create shared_ptr object from memory from stack instead of heap.

Checkout below example,

shared_ptr expects that memory associated with it is from heap, therefore when it goes out of scope it deletes the associated memory if reference count is 0. But in above example we associated the memory from stack to shared_ptr object and in its destructor this shared_ptr object will call delete operation on this memory. As this memory was from stack not from heap, so our program will crash.

Hence, its advised not to create shared_ptr from raw pointers directly. Instead of that we should use make_shared<> like,