How to solve dangling pointer problem with smart pointers
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 illustrates this situation:
MyClass* p(new MyClass); MyClass* q = p; delete p; p->DoSomething(); // Watch out! p is now dangling! p = NULL; // p is no longer dangling q->DoSomething(); // Ouch! q is still dangling!
For auto_ptr, this is solved by setting its pointer to NULL when it is copied:
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; So only one object will be responsible to cleanup the memory and other smart pointer object pointer will point to NULL.
What are smart pointers in C++ ?
Filed under: C++ Interview Questions, Microsoft Interview Questions
Smart pointers are objects that look and feel like pointers, but are smarter.
They have the same interface same interface that pointers do: they need to support pointer operations like dereferencing (operator *) and indirection (operator ->). An object that looks and feels like something else is called a proxy object, or just proxy
Smart pointer get deleted when it goes out of scope
The simplest example of a smart pointer is auto_ptr, which is included in the standard C++ library. You can find it in the header <memory> . Here is part of auto_ptr’s implementation, to illustrate what it does:
template <class T> class auto_ptr { T* ptr; public: explicit auto_ptr(T* p = 0) : ptr(p) {} ~auto_ptr() {delete ptr;} T& operator*() {return *ptr;} T* operator->() {return ptr;} // ... }; auto_ptr is a simple wrapper around a regular pointer. It forwards all meaningful operations to this pointer (dereferencing and indirection). Its smartness in the destructor: the destructor takes care of deleting the pointer Below is one of the usage of auto_ptr smart pointervoid foo() { MyClass* p(new MyClass); p->DoSomething(); delete p; }You can write:
void foo() { auto_ptr<MyClass> p(new MyClass); p->DoSomething(); }
