tags:

views:

223

answers:

7

What makes smartpointers better than normal pointers?

+11  A: 

They simplify the problem of resource management. Once you hold your resources within smart pointers they will release memory for you when they go out of scope applying RAII techniques.

This has two main advantages: code is safer (less prone to resource leaks) and programming is easier as you do not need to remember in each part of your code whether the resource you are holding must be manually released.

David Rodríguez - dribeas
"they will release memory for you when they go out of scope" ... true for i.e. std::auto_ptr, but not for smart pointers based on other policies like ref-counting.
Georg Fritzsche
+3  A: 

Automatic reference counting and deallocation.

Mehrdad Afshari
Especially in the face of exceptions!
D.Shawley
+7  A: 

The principal advantage is that the memory pointed to by the smart pointer will be automatically deallocated when the pointer does out of scope. With regular pointers, you have to manage the memory yourself.

Paul Lalonde
+1  A: 

Have a look at:

Smart Pointers

Koekiebox
+5  A: 

Fewer memory leaks. Maybe Scott Meyers can make it clearer for you:

  1. Effective C++
  2. More Effective C++
duffymo
+7  A: 

A raw pointer doesn't take ownership of the resource it points to. When the pointer goes out of scope, the object it pointed to is unaffected. Often, you want some kind of ownership semantics where, when the pointer goes out of scope, the object it points to should either be deleted, or at least be notified that there's one less pointer pointing to it.

That is what smart pointers do.

A shared_ptr implements reference-counting, so that when all pointers to an object are destroyed, the object gets deleted.

Others, like scoped_ptr or unique_ptr or auto_ptr implement various forms of exclusive ownership. When a scoped_ptr is destroyed, it deletes the object it points to.

jalf
+1 for the one answer that explains and also does reduce smart pointer to 1 or 2 smart pointer policies.
Georg Fritzsche
s/does/does not/
Georg Fritzsche
+2  A: 

While agreeing with the other answers in practice, I'd just like to say that nothing makes smart pointers better in principle, unless they happen to be what works for your application. That is, if a smart pointer isn't needed, it isn't better.

If the smart pointer you're talking about is std::auto_ptr, it could well be substantially worse than a simple pointer. But that's not so much a smart pointers issue as a semantics of assignment issue.

That said, smart pointers very often are useful - even the dreaded auto_ptr - especially (as mentioned above) WRT exception safety.

Steve314