To be smarter than regular pointers, smart pointers need to do things that regular pointers don't. What could these things be? Probably the most common bugs in C++ (and C) are related to pointers and memory management: dangling pointers, memory leaks, allocation failures and other joys. Having a smart pointer take care of these things can save a lot of aspirin...
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
template
{
T* ptr;
public:
explicit auto_ptr(T* p = 0) : ptr(p) {}
~auto_ptr() {delete ptr;}
T& operator*() {return *ptr;}
T* operator->() {return ptr;}
// ...
};
As you can see, 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.
- pradeep T
- chennai, India
-
▼
2012
(7)
- ► 03/04 - 03/11 (3)
-
►
2009
(12)
- ► 02/15 - 02/22 (2)
- ► 02/08 - 02/15 (10)
-
►
2008
(2)
- ► 09/07 - 09/14 (1)
- ► 08/24 - 08/31 (1)
About Me
Blog Archive
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment