Smart pointer is a variation of RAII. RAII means resource acquisition is initialization. Smart pointer acquires a resource (memory) before usage and then throws it away automatically in a destructor. Two things happen:
- We allocate memory before we use it, always, even when we don't feel like it -- it's hard to do another way with a smart pointer. If this wasn't happening you will try to access NULL memory, resulting in a crash (very painful).
- We free memory even when there's an error. No memory is left hanging.
For instance, another example is network socket RAII. In this case:
- We open network socket before we use it,always, even when we don't feel like -- it's hard to do it another way with RAII. If you try doing this without RAII you might open empty socket for, say MSN connection. Then message like "lets do it tonight" might not get transferred, users will not get laid, and you might risk getting fired.
- We close network socket even when there's an error. No socket is left hanging as this might prevent the response message "sure ill be on bottom" from hitting sender back.
Now, as you can see, RAII is a very useful tool in most cases as it helps people to get laid.
C++ sources of smart pointers are in millions around the net including responses above me.