We are committed to provide service 24 X 7

Deals, Shopping, Training, Tools

C++11 Smart Pointer – Part 4: Create shared_ptr objects carefully

We should create shared_ptr objects carefully.


Checkout below two cases,


[showads ad=inside_post]

Advertisements

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,

int * rawPtr = new int();
std::shared_ptr<int> ptr_1(rawPtr);
std::shared_ptr<int> ptr_2(rawPtr);

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,

#include<iostream>
#include<memory>
typedef struct Sample {
Sample() {
    internalValue = 0;
    std::cout<<"Constructor"<<std::endl;
}
~Sample() {
    std::cout<<"Destructor"<<std::endl;
}
}Sample;
int main()
{
    {
    Sample * rawPtr = new Sample();
    std::shared_ptr<Sample> ptr_1(rawPtr);

        {
        std::shared_ptr<Sample> ptr_2(rawPtr);
        }
// As ptr_2 dont know that the same raw pointer is used by another shared_ptr i.e. ptr_1, therefore
// here when ptr_2 goes out of scope and it deletes the raw pointer associated with it.

// Now ptr_1 is internally containing a dangling pointer. Therefore when we it
// will go out of scope it will again try to delete the already deleted raw pointer and application
// will crash.
    }
return 0;
}

 

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

Checkout below example,

#include<iostream>
#include<memory>

int main()
{
int x = 12;
std::shared_ptr<int> ptr(&x);
return 0;
}

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,

std::shared_ptr<int> ptr_1 = make_shared<int>();

std::shared_ptr<int> ptr_2 (ptr_1);

Cart

Your Cart is Empty

Back To Shop