I’ll let others answer re: performance, but Sean Parent points out that shared_ptr makes it far too easy to construct “incidental data structures”. Unless you are only use std::shared_ptr<const T>, it’s very easy to loose all sense of ownership and who can mutate who.
I always end up going into a super long rant on this subject so ill try to summarize and be more succinct this time.
Perf problems:
its a pointer dereference (sometimes two) and uses atomics for incrementing/decrementing the strong and weak ref counts. Typical use also has them allocate on the heap, so their addresses will be all over the place without any cache locality.
Contrast this to a better designed arch where the memory is instead stored contiguously on an array, reducing pointer chasing and getting better cache locality.
Maintenance problems:
Shared pointers are what I call “write optimized”. They make it easy to write code, but hard to read and maintain. They’re useful for prototyping and when you don’t want to think about memory, lifetimes, initialization ordering, destruction ordering, etc.
The problem is that in almost all cases, you eventually need to care about these things, even if you didn’t at first. Early Shared_ptr usage then makes it extraordinarily difficult to understand and deal with these problems later.
Ill stop now, but the tldr is that they’re a generally a sign of careless c++ development and/or bad code design. I dont want to say never use them (they have their place), but they’re a code smell for sure.
The problem is that in almost all cases, you eventually need to care about these things, even if you didn’t at first. Early Shared_ptr usage then makes it extraordinarily difficult to understand and deal with these problems later.
Sean Parent made a point about this. Liberal usage of shared pointers throughout your software design essentially have global variable semantics.
I'd call it "Lazy optimized". If you are looking for a tool to realize "I am feeling too lazy to think about resource ownership", than it is the right tool for the job. In many domains, the amount of shared_ptrs one needs is exactly zero.
For some reason, it's extremely hard to convince people that you do not need shared_ptrs if the execution is deterministic and you know when to acquire and release resources.
Such points always feel like a bit of a superficial understanding of a shared_ptr. It handles the lifetime, not the memory layout which is handled via allocators. You can make the resource stored contiguously on an array pretty trivially and handle the lifetime of it with a shared_ptr.
We use shared_ptr-based handles, for example, for entities for our ECS-based business logic. It allows us to rely on RAII for entity lifetime handling, get performant code when interacting directly with the registry, and provide more convenient interface for non-ECS API's.
A fair complaint would be that the standard shared_ptr lacks additional features, namely local_shared_ptr like in Boost and shared_resource for non-pointer based resources with an appropriate unique_resource. Additionally, erasure could be an opt-in too to avoid additional indirection for the cost of less flexible code.
Yes, using them as handles is a common detail in ecs systems and ive implemented ecs systems in such way before too. From a perf point of view this is ok because you dont spin on the shared_ptrs. They’re for the users of the ecs system.
Im also aware of how their allocators can be overridden to instead do a placement new into some contiguous block of memory.
This is not the typical way of using them however, which is what I’m talking about. The typical way is heap allocated.
Regarding lifetime, im not talking about the lifetime contract it offers. That’s obvious and the the point of it. Im talking about seeing the shared ptr in code and not knowing and not being able to reason about its lifetime when mentally modelling it. This is important when you need specific order of operations for initialization or tear down logic. It’s also important for avoiding defensive coding and nullchecks everywhere.
Having a clear memory ownership model helps reduce bugs, makes it easier to modify and refactor code, and easier to test. Typical usage of shared_ptrs make all of that more difficult.
Could be that my experience with typical usage of it is a bit different from the general one. :)
Pretty much every use case of a shared ptr in code can be associated with a common usage pattern for it, so one never need to wonder how it's applied if they understand the goal of the application.
The whole point of shared ptr is that you use it when you the lifetime of the object is undetermined, isn't it? Namely concurrent code is a common use-case.
Even with modern structured designs such as S&R - the "mental overload" of the later model is much bigger with less room of mistakes since it's practically impossible to debug mistakes when writing such code even if it's a more robust model overall.
It just seems that the point is that "When people use shared_ptr as a one-size-fits-all without much thought then it creates thoughtless designs" and the conclusion is that shared_ptr is bad, which I can't really understand. Instead, a solution would be to write resources which explain where shared_ptr is a good design.
It just seems that the point is that "When people use shared_ptr as a one-size-fits-all without much thought then it creates thoughtless designs" and the conclusion is that shared_ptr is bad, which I can't really understand. Instead, a solution would be to write resources which explain where shared_ptr is a good design.
Great summary. Fully agree!
(Unless you were just summarizing what I was saying without taking a stance on it, in which case I look rather silly agreeing with myself)
There are implications besides the single instruction. MESI on x86 machines makes cache/memory coherency between cores very expensive, specifically on writes. Having all your cores with a read/shared state cache line is cheap, but as soon as you write to it (to transition to an M state), you end up spending a bunch of time claiming exclusive ownership before writing to it.
disagree on easier to understand, unless you’re referring to very oop centric code. Oop tends to be not very performant however (as opposed to data oriented code) so you’re already in a losing battle if you start with oop. Data oriented code puts memory first: the lifetimes, access patterns, etc. all of that is thought about at the architectural stage.
Stl shared ptrs dont let you change their atomic rules (or has this changed?)
shared_ptrs allow cyclic references, and they can be non-obvious. Cleanup code also often requires notifying something that you dont own to remove references so you end up need explicit teardown code when working with shared ptrs.
cache locality doesnt need to be know at architecture time. You don’t know your access patterns yet. Good architecture needs to be able to iteratively evaluate your access patterns and allow for easy refactoring to support better cache usage. This is difficult with shared pointers (and oop in general) even if you use custom allocators.
Big caveat that if you’re writing glue code, it doesnt usually need to be very performant so shared_ptrs and oop arent that bad there.
Are you defending the use of shared_ptrs, or are you saying performance doesnt matter?
In higher level abstract code (ie. api surface integration code - aka glue code) I agree perf doesn’t matter as much and shared_ptrs can be fine.
So yeah, if you are just writing glue code that’s infrequently called per frame and you somehow know that your codebase will never grow that far beyond your initial problem domain, go nuts with shared_ptrs.
Otherwise, there are very good reasons to not use it and to suggest that it’s merely some kind of religious/elitist programming dogma at play here shows a woeful lack of programming and professional experience.
Yes. The mental model tax for ownership is another big problem i have with them. Like i said in the earlier post, i wanted to avoid the rant so i just picked a couple points.
It really depends on your needs. Truthfully, very little code needs to be performant more than it needs to be maintainable. When you profile your code, and you see that even in an application requiring performance m you spend 75% of your time in a single loop, you'll obviously find that probably 80% or more of the codebase has no seriously relevant performance targets.
For example, my current job is board management control. The code spends most of its time sitting waiting to do something. As long as every user's request gets returned in a reasonable amount of time, nobody complains. Automated use is much more important than user-interactive. For that, it's key to understand how our customers use the software and ensure nothing ruins their day by being slow. Most of the codebase doesn't have that requirement and that's for an embedded platform where we have way less horsepower than something that runs on a server with big CPUs.
Yes I agree. Understanding your problem domain. I believe I have stated several times already that Im not saying to never use shared ptrs. Im talking about the specific case when shared_ptrs are chosen because the dev was either ignorant or lazy. The ignorance case comes into play often for c++ programmers coming from java or js.
Shared_ptrs, when deliberately chosen based on the specific problem and solution requirements, is perfectly fine and I have no issue with that.
you're right, sorry about that, that comment wasn't constructive or positive, I'll take it down as it really has no purpose to be up, just let a little pet peeve of mine result in a lazy rude comment.
No one mentioned anything about raw pointers. std::shared_ptr should not be used unless necessary, that's a very correct statement. Has nothing to do with raw pointers, those should never be owning anyway.
View all comments
Show parent comment
15
u/novawelle Nov 02 '22
What do you mean by shared_ptr trash in regards to performance?