What makes smartpointers better than regular pointers?
They simplify the resource management problem. When you keep your resources in smart pointers, they will free memory for you when they go out of scope using RAII techniques .
This has two main advantages: the code is more secure (less prone to resource leaks), and programming is easier since you don't have to remember in every part of your code whether a resource has to be manually released.
source to share
A raw pointer does not acquire ownership of the resource it points to. When a pointer goes out of scope, the object it pointed to does not change. Often you need some kind of semantics of your own, where when a pointer goes out of scope, the object it points to should be removed, or at least should be notified that the pointer is less than the pointer to it.
That's what smart pointers do.
A shared_ptr
implements reference counting, so when all pointers to an object are destroyed, the object is deleted.
Others, such as scoped_ptr
either or unique_ptr
or auto_ptr
, exercise various forms of exclusive ownership. When a is scoped_ptr
destroyed, it removes the object it points to.
source to share
While agreeing with the other answers in practice, I just want to say that nothing makes smart pointers better in principle, unless they work for your application. That is, if a smart pointer is not needed, it is no better.
If the smart pointer you are talking about is std :: auto_ptr, it can be significantly worse than a simple pointer. But these are not so much smart pointers as the semantics of the assignment problem.
That said, smart pointers are very often useful - even the dreaded auto_ptr - especially (as mentioned above) the security of WRT.
source to share