Reputation: 3287
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?
Upvotes: 4
Views: 2183
Reputation: 109119
The code in your question contains 2 conflicting definitions of p
. I'm assuming you meant to post something like
int* p = new int(10);
std::shared_ptr<int> p1(p);
delete p;
When the shared_ptr
goes out of scope and its reference count falls to zero it will attempt to delete p;
, leading to double deletion and undefined behavior.
You've passed ownership of the dynamically allocated int
to the shared_ptr
, so let it do its job, and don't go about deleting the int
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 instance
template<typename T, typename... Args>
void api_func(Args&&... args)
{
auto p = std::make_shared<T>(std::forward<Args>(args)...);
// Use the shared_ptr p as before
}
Then, instead of passing a shared_ptr<int>
, client code would call the above function as api_func<int>(10);
.
Upvotes: 6