Search code examples
c++shared-ptrsmart-pointers

Dangling reference for smart pointer in C++


I understand that in C++ it is best/safer to use smart pointers in order to make sure we never miss freeing/deleting the allocated memory. Now I recently came across the following in a lecture about smart pointers in C++. This is the example:

void test_pointer(void)
{
    typedef std::shared_ptr<MyObject> MyObjectPtr;
    MyObjectPtr p1; // Empty

    {
        MyObjectPtr p2(new MyObject());
        p1 = p2;
    }
}

Now I understand that std:shared_ptr will be destroyed after the last reference of it is done, ie after we exit the function p1 will be destroyed. But the warning at the end was about a dangling reference, which is what confused me:

MyObjectPtr* pp = new MyObjectPtr(new MyObject());

The Note mentions that if this was declared within the function then it is a dangling reference, which prevents the std::shared_ptr from ever being deleted. Why is that? We are using smart pointers so we should never end up in this situation?


Solution

  • I just realized it (and please correct me if I'm wrong):

    We are using a raw pointer to the std::shared_ptr which is never being freed which is what is causing the issue. It is never been freed. and since this is happening with in the function then it prevents p1 as well from being destroyed.