I take the following approach:
- Stack by default
- Unique ptr if needed on the heap
- Shared ptr if needed to share ownership
Although unique ptr is zero cost after make_unique(), I avoid polluting my heap unnecessarily. I've never benchmarked this though (keeping various objects on stack vs heap as unique ptr and how that impacts memory accesses)
I'm quite junior. Appreciate anyone pointing out if anything I said doesn't make sense.
> Stack by default - Unique ptr if needed on the heap - Shared ptr if needed to share ownership
Sounds about right. Shared ownership is fairly rare though, and you often only need shared access (reference/pointer if nullable) and can provide other, more explicit, ways of managing the lifetime.
> unique ptr is zero cost after make_unique()
Kind of, but compared to the stack, it could cause caching inefficiency because your heap-allocated thing could be almost anywhere, but your stack-allocated thing is probably in the cache already.
Although unique ptr is zero cost after make_unique(), I avoid polluting my heap unnecessarily. I've never benchmarked this though (keeping various objects on stack vs heap as unique ptr and how that impacts memory accesses)
I'm quite junior. Appreciate anyone pointing out if anything I said doesn't make sense.