Reputation: 511
I understand that in C++ it is best/safer to use smart pointers in order to make sure we never miss freeing/deleting the allocated memory. Now I recently came across the following in a lecture about smart pointers in C++. This is the example:
void test_pointer(void)
{
typedef std::shared_ptr<MyObject> MyObjectPtr;
MyObjectPtr p1; // Empty
{
MyObjectPtr p2(new MyObject());
p1 = p2;
}
}
Now I understand that std:shared_ptr
will be destroyed after the last reference of it is done, ie after we exit the function p1
will be destroyed. But the warning at the end was about a dangling reference, which is what confused me:
MyObjectPtr* pp = new MyObjectPtr(new MyObject());
The Note mentions that if this was declared within the function then it is a dangling reference, which prevents the std::shared_ptr
from ever being deleted. Why is that? We are using smart pointers so we should never end up in this situation?
Upvotes: 1
Views: 1182
Reputation: 44248
How come? We are using smart pointers so we should never end up in this situation?
You are not. Here:
MyObjectPtr* pp = new MyObjectPtr(new MyObject());
You are using raw pointer to an object which type is a smart pointer. But it does not mater what kind of object you allocate manually and keep in raw pointer - you have to manage that object lifetime manually. Or use a smart pointer.
Upvotes: 3
Reputation: 511
I just realized it (and please correct me if I'm wrong):
We are using a raw pointer to the std::shared_ptr
which is never being freed which is what is causing the issue. It is never been freed. and since this is happening with in the function then it prevents p1 as well from being destroyed.
Upvotes: 3