SLIDE 3 The Smart Pointer
- The smart pointer should look and act
like a regular pointer:
– Should support -> – Should support *
- Should be smarter than your average pointer.
– Reduce memory leaks – Reduce dangling pointers – Take ownership
auto_ptr
- STL has a standard smart pointer that is a
wrapper around a regular pointer
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
- What makes auto_ptr smart is that it takes
- wnership of the pointer and cleans up
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;} // ... };
Using auto_ptr
Instead of
void foo() { MyClass* p(new MyClass); p->DoSomething(); delete p; }
Use
void foo() { auto_ptr<MyClass> p(new MyClass); p->DoSomething(); }
p will cleanup after itself
Why use auto_ptr?
– Reduces memory leaks
– Includes a default constructor that sets pointer to NULL
Why use auto_ptr?
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!