SomeUser
SomeUser

Reputation: 2041

What makes smartpointers better than normal pointers?

What makes smartpointers better than normal pointers?

Upvotes: 2

Views: 310

Answers (7)

user180247
user180247

Reputation:

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.

Upvotes: 2

Stack Overflow is garbage
Stack Overflow is garbage

Reputation: 248129

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.

Upvotes: 7

duffymo
duffymo

Reputation: 308928

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

  1. Effective C++
  2. More Effective C++

Upvotes: 5

Koekiebox
Koekiebox

Reputation: 5963

Have a look at:

Smart Pointers

Upvotes: 1

Paul Lalonde
Paul Lalonde

Reputation: 5050

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.

Upvotes: 7

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422112

Automatic reference counting and deallocation.

Upvotes: 3

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.

Upvotes: 11

Related Questions