Writing a simple JSON library from scratch: a tour through modern C++
Good modern C++ uses <i>shared_ptr</i> very, very sparingly. Most programs do not use it at all. Overuse of <i>shared_ptr</i> is called Java Disease.<p><i>unique_ptr</i> is, at base, <i>very simple</i>. A variable of this type owns whatever it points at. Since only one pointer can own the memory, ownersip passes from one instance to the next &quot;by move&quot;. It is easy to know, at any place in the code, which owns the pointed-at thing.<p>It is generally a mistake to expose <i>unique_ptr</i> in an interface. It is an implementation primitive. Very often a class has only just one data member, a <i>unique_ptr</i> to a private-typed object in storage. Users of the type treat it as an ordinary value, but don&#x27;t need to know anything at all about the implentation object. All the code that operates on it can be off in a &quot;.cc&quot; file, and you can change it without need to rebuild clients.<p>A vector of unique_ptr is another common class member, to hold ownership of a bunch of objects.<p>Once in a great while you want to take over control of how the memory is released when an owning <i>unique_ptr</i> goes out of scope. Maybe the memory was allocated with <i>mmap</i> and must be freed with <i>munmap</i>. This is easy to do with one-liner functions, or lambdas.