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();
}
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…
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With