Hacker News new | past | comments | ask | show | jobs | submit login

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.


Author here, that's a good approach :-). I see shared_ptr as a code smell since shared ownership makes life difficult.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: