Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Use <code>unique_ptr&lt;T&gt;</code> all the time except when you need reference counting, in which case use <code>shared_ptr&lt;T&gt;</code> (and for very rare cases, <code>weak_ptr&lt;T&gt;</code> to prevent reference cycles). In almost every case, transferrable unique ownership is just fine.</p> <p>Raw pointers: Good only if you need covariant returns, non-owning pointing which can happen. They're not terrifically useful otherwise.</p> <p>Array pointers: <code>unique_ptr</code> has a specialization for <code>T[]</code> which automatically calls <code>delete[]</code> on the result, so you can safely do <code>unique_ptr&lt;int[]&gt; p(new int[42]);</code> for example. <code>shared_ptr</code> 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 <code>std::vector</code> anyway. Unfortunately <code>shared_ptr</code> does not provide an array access function, so you'd still have to manually call <code>get()</code>, but <code>unique_ptr&lt;T[]&gt;</code> provides <code>operator[]</code> instead of <code>operator*</code> and <code>operator-&gt;</code>. In any case, you have to bounds check yourself. This makes <code>shared_ptr</code> slightly less user-friendly, although arguably the generic advantage and no Boost dependency makes <code>unique_ptr</code> and <code>shared_ptr</code> the winners again.</p> <p>Scoped pointers: Made irrelevant by <code>unique_ptr</code>, just like <code>auto_ptr</code>.</p> <p>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.</p> <p>There are still uses for other smart pointers, like <code>intrusive_ptr</code> or <code>interprocess_ptr</code>. However, they're <em>very</em> niche and completely unnecessary in the general case.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload