I'm currently learning about the unique_ptr
and shared_ptr
types in C++. The advantages of smart pointers over raw pointers are apparent, and there are lots of explanations why you should prefer them over raw pointers. What I'm struggling to understand is why you would ever specifically choose to use a unique_ptr
over a shared_ptr
?
As far as I can tell, from the programmers perspective (ignoring implementation) , a unique_ptr
just seems like a special-case version of a shared_ptr
where the reference count is restricted to one. So if I create a shared_ptr
and only ever create a single reference, then I basically have the utility of a unique_ptr
(with the ability to use the shared
part in the future).
So what advantage does a unique_ptr
give you? I should admit that I approach this as a Java programmer and a shared_ptr
seems pretty darn close to the way Java works.