Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of a unique_ptr over a shared_ptr

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_ptrjust 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.

like image 782
J-bob Avatar asked Sep 30 '19 19:09

J-bob


1 Answers

a unique_ptr just seems like a special-case version of a shared_ptr where the reference count is restricted to one

This is not true, and is the crux of why you would use one or another. A shared_ptr is a reference counted pointer. In order for it to be thread safe it uses an atomic counter for the reference count. So that means for a shared_ptr you have the extra overhead of storing the reference counter, plus the execution overhead of checking/manipulating that counter in all the functions that affect it. This overhead can make a noticeable impact on performance

A unique_ptr, conversely, is a non reference counted pointer. It can get away without having a reference counter because it is not copyable. That means it is basically a zero cost abstraction for newing and deleteing a pointer.

So, if you never need to share ownership, or you can just move it from place to place, and you want self management, then you want a unique_ptr. This covers the vast majority of pointer use cases. When you truly need shared ownership then you can go ahead and use shared_ptr, but understand you suffer a performance penalty for that shared ownership.

like image 172
NathanOliver Avatar answered Oct 24 '22 07:10

NathanOliver