Tom Ritchford
1 min readApr 8, 2023

--

Good article, accept claps.

So I cannot claim to have read all the assembly code but this was very informative and reaffirmed my general ideas: std::shared_ptr is pretty amazing, and given the fanciness of what it does, it isn't so expensive, but it isn’t free either. Most of the time you don’t care because it’s pretty cheap.

But there are other risks in shared pointers which are more serious.

With std::shared_ptr, you really have no idea when where or where the destructor of the underlying class is going to be called. In particular, it might even be that the destructor is occasionally called on a thread different from the thread that constructed the object, and in some cases this is problematic.

It is my belief that easily 90% of the time that people use std::shared_ptr, they could do the job with std::unique_ptr and references.

In new C++ development I've been involved in, only once was a shared pointer necessary, when I was writing a Python library: I literally doled out pointers to the Python world, and they might get copied, and I had no idea when they would come back to me..

And I worked on one other project, a distributed ledger, where the ledger elements were shared pointers, which was also unavoidable.

But the rest of the time, each data item had or could have had a unique owner, and a well-defined scope, so you could literally point to the line where it would be deleted.

Thanks again for some good reading!

--

--

Responses (1)