Chris
Chris

Reputation: 115

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

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();
}

Upvotes: 4

Views: 1477

Answers (3)

Jesper Juhl
Jesper Juhl

Reputation: 31457

"What happens to a raw pointer if it's shared_ptr is deleted?" - Nothing. It just becomes invalid to subsequently use that pointer.

"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?"

No. It is not valid to then use the raw pointer. And the raw pointer does not change (to nullptr) to indicate that the pointed-to object has been deleted.

It is your responsibility to ensure, that if something like that happens, you do not use the raw pointer after it has been invalidated. How you do that is up to you - the language doesn't care/help you.

Using the raw pointer after the object it points to has been deleted, is Undefined Behaviour.

Upvotes: 2

Mike Vine
Mike Vine

Reputation: 9837

It can sometimes be useful to think of smart pointers as a delayed delete mechanism. What I mean by that is that if you allocate a class and give it to a smart pointer you are basically asking the smart pointer class to delete that pointer sometime in the future. For a shared_ptr that time in the future is when no more shared_ptrs exist for it.

Applying this to your code, you create a shared_ptr. You then return the raw pointer. Then your function ends and the only shared_ptr to that pointer gets destroyed and so the underlying class is deleted.

This makes your question "If I new a class and delete it then return the original pointer what happens". Which is a lot easier to answer and the answer to that is "badness". There are many answers to this question on stack overflow - such as C++ delete - It deletes my objects but I can still access the data?

Upvotes: 2

Michael Kenzel
Michael Kenzel

Reputation: 15943

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…

Upvotes: 4

Related Questions