1

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?

1
  • 1
    The sanity of a manually managed pointer to a smart pointer is something you should probably consider a tremendous code smell.
    – WhozCraig
    Apr 9, 2020 at 21:00

2 Answers 2

3

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.

1
3

How come? We are using smart pointers so we should never end up in this situation?

You are not. Here:

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

You are using raw pointer to an object which type is a smart pointer. But it does not mater what kind of object you allocate manually and keep in raw pointer - you have to manage that object lifetime manually. Or use a smart pointer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.