Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How efficient smart pointers are?

I know, that std::shared_ptr uses reference counting, so it has copy&move semantics, on the other hand std::unique_ptr (hence the name unique) only has move semantics, so trying to copy it is a compile error.

However, its not quite clear for me how big of a deal is that. Can I simply use std::shared_ptr over std::unique_ptr in most cases, or should I use std::unique_ptr whenever possible, as it's far more efficient because it doesn't have to take care of reference counting?

Also, I know that smart pointers are useful when dealing with, for example exception safety, but are they a mean to generally replace traditional T* pointers? Is it a good programming practice to use smart pointers over traditional T* pointers whenever possible?

like image 303
krispet krispet Avatar asked Dec 04 '25 23:12

krispet krispet


2 Answers

The rule of thumb is:

  1. If you can, use a stack based object directly or by a reference instead of using pointers.
  2. Else, if you don't have to deal with shared ownership (usually you don't) use unique_ptr - it is not only faster, but also safer (no circular references).
  3. Else, if you do have shared ownership, use shared_ptr

Raw pointers are OK in certain circumstances when they don't carry ownership - for instance as an input argument to a function:

void draw (const shape* sh) {
    sh->draw();
}

...
std::unique_ptr<shape> ptr(new triangle);
draw(ptr.get());
like image 101
Nemanja Trifunovic Avatar answered Dec 06 '25 14:12

Nemanja Trifunovic


The problem with the shared_ptr is, that, afaik, the reference counting is an atomic function, that means it not only counts the references, but also has locking functionality to ensure that the function is atomic. So at that point, yes, unique_ptr is better to use, when you only need move functionality.

Personally, I dont use shared_ptr alot, mostly normal pointers are enough. Imho smart pointers are only encourage getting lazy in memory management. I was in projects where smart pointers only caused race conditions when quitting the program, because nobody knew the order of destruction and these pointers referenced each others. For myself, I only use them if a lib of mine is putting pointers to the outside for which it is irrelevent when they get deleted (or in which order).

like image 43
Nidhoegger Avatar answered Dec 06 '25 13:12

Nidhoegger