Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to a raw pointer if it's shared_ptr is deleted?

Tags:

c++

What happens if a C/C++ API returns a raw pointer from an internally used shared_ptr, then the shared_ptr gets "deleted"? Is the raw pointer still valid? How can the API developer clean up the raw pointer when it's not in their control anymore?

As an example:

MyClass* thisReturnsAPtr()
{
    std::shared_ptr<MyClass> aSharedPtr = std::make_shared<MyClass>(MyClass);
    return aSharedPtr.get();
}
like image 499
Adam Avatar asked Oct 28 '25 07:10

Adam


1 Answers

If there are no other shared_ptr around anymore that still hold a reference to the object and, thus, keep the object alive, then the object will be destroyed, the memory freed, and any still existing pointer that pointed to that object will become a dangling pointer.

In your example above, the pointer returned by the function thisReturnsAPtr is guaranteed to be an invalid pointer…

like image 143
Michael Kenzel Avatar answered Oct 31 '25 11:10

Michael Kenzel