I was reading about smart pointers in C++ and saw this example given as how smart pointers handle "dangling pointer" problem if normal pointers are used. P.S. I know auto_ptr is deprecated by C++ 2011 but it still has unique_ptr or some such equivalent of it.
Dangling pointers. A common pitfall of regular pointers is the dangling pointer: a pointer that points to an object that is already deleted. The following code(jsut for example purpose) illustrates this situation:
MyClass* p(new MyClass);//Assume we have a MyClass definition available
MyClass* q = p;
delete p;
p->DoSomething();
p = NULL; // p is not dangling anymore
q->DoSomething(); // Don't.. q is still dangling!
Using auto_ptr, this is solved by setting its pointer to NULL when it is copied (Copy constructor implemented as below):
template <class T>
auto_ptr<T>& auto_ptr<T>::operator=(auto_ptr<T>& rhs)
{
if (this != &rhs) {
delete ptr;
ptr = rhs.ptr;
rhs.ptr = NULL;
}
return *this;
}
And now if we have the same code using auto_ptr as below:
auto_ptr<MyClass> p(new MyClass);
auto_ptr<MyClass> q = p;
delete p;
p->DoSomething();
p = NULL;
q->DoSomething();
I get the logic in the aqbove copy constructor but how does making the rhs.ptr = NULL help. I mean if one dereferences this pointer later (q in above code example), it would crash as it is made NULL by the smart pointer copy constructor.
Where as what would have happened if it was a normal pointer and we would have dereferenced a dangling pointer? Some undefined behavior maybe. But how does using auto_ptr help
new
up one object. Point with two different pointers at it.delete
it and then call a method on it. – pmrstd::auto_ptr
isn't a legal implementation (and would fail on self-assignment if it were), and the last example does adelete
on an auto_ptr, which shouldn't even compile. – James Kanze