简体   繁体   中英

What makes smartpointers better than normal pointers?

是什么让smartpointers比普通指针更好?

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.

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.

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.

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

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

自动引用计数和释放。

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.

Have a look at:

Smart Pointers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM