What makes smartpointers better than regular pointers?

What makes smartpointers better than regular pointers?

+2


source to share


7 replies


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.

+11


source


The main advantage is that the memory pointed to by the smart pointer is automatically freed when the pointer goes out of scope. With ordinary pointers, you have to manage the memory yourself.



+7


source


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.

+7


source


Less memory leaks. Perhaps Scott Meyers can make this clearer for you:

+5


source


Automatic reference counting and freeing.

+3


source


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.

+2


source


Take a look:

Smart pointers

+1


source







All Articles