If I do the following,
int* p = new int(10);
std::shared_ptr<int>(p);
delete p;
What happens here? Is the shared_ptr
invalid after deletion of the raw pointer? Is there any way to ensure memory access safety in such a scenario?
If I do the following,
int* p = new int(10);
std::shared_ptr<int>(p);
delete p;
What happens here? Is the shared_ptr
invalid after deletion of the raw pointer? Is there any way to ensure memory access safety in such a scenario?
The code in your question contains 2 conflicting definitions of
p
. I'm assuming you meant to post something likeWhen the
shared_ptr
goes out of scope and its reference count falls to zero it will attempt todelete p;
, leading to double deletion and undefined behavior.You've passed ownership of the dynamically allocated
int
to theshared_ptr
, so let it do its job, and don't go about deleting theint
yourself.If you want clients of your API from doing something similar to the code above, one possibility is to change the API function's parameter type from a
shared_ptr
to a parameter pack of constructor arguments. For instanceThen, instead of passing a
shared_ptr<int>
, client code would call the above function asapi_func<int>(10);
.