Which kind of pointer do I use when?

后端 未结 4 1021
遥遥无期
遥遥无期 2020-11-22 03:39

Ok, so the last time I wrote C++ for a living, std::auto_ptr was all the std lib had available, and boost::shared_ptr was all the rage. I never rea

4条回答
  •  伪装坚强ぢ
    2020-11-22 04:12

    Use unique_ptr all the time except when you need reference counting, in which case use shared_ptr (and for very rare cases, weak_ptr to prevent reference cycles). In almost every case, transferrable unique ownership is just fine.

    Raw pointers: Good only if you need covariant returns, non-owning pointing which can happen. They're not terrifically useful otherwise.

    Array pointers: unique_ptr has a specialization for T[] which automatically calls delete[] on the result, so you can safely do unique_ptr p(new int[42]); for example. shared_ptr you'd still need a custom deleter, but you wouldn't need a specialized shared or unique array pointer. Of course, such things are usually best replaced by std::vector anyway. Unfortunately shared_ptr does not provide an array access function, so you'd still have to manually call get(), but unique_ptr provides operator[] instead of operator* and operator->. In any case, you have to bounds check yourself. This makes shared_ptr slightly less user-friendly, although arguably the generic advantage and no Boost dependency makes unique_ptr and shared_ptr the winners again.

    Scoped pointers: Made irrelevant by unique_ptr, just like auto_ptr.

    There's really nothing more to it. In C++03 without move semantics this situation was very complicated, but in C++11 the advice is very simple.

    There are still uses for other smart pointers, like intrusive_ptr or interprocess_ptr. However, they're very niche and completely unnecessary in the general case.

提交回复
热议问题