Hacker News new | ask | show | jobs
by kentonv 911 days ago
This sounds nice but it just isn't realistic. If you try to write a complex system in C++ without non-owning references, you're basically heap-allocating every single object and using slow atomic refcounting everywhere. Performance will likely be much worse than just using a garbage collected language to start with.
1 comments

Worrying about the speed of smart pointer reference counting sounds like premature optimization at best. If this is really what's slowing your app down in 2023, then you've got bigger problems than choosing owning vs non-owning references.
Again, if you aren't worried about this you might as well be using a garbage collected language. They are generally faster than using atomic reference counting for everything. But people use C++ (or Rust) for a reason.

FWIW I don't work on an "app", I work on a cloud platform that hosts web apps, operating in hundreds of datacenters and serving millions of requests per second. Small optimizations are worth a lot of money here -- and garbage collection is a nonstarter in this kind of systems work, for more reasons than just performance.

Well, there are exceptions to everything, but for the vast majority of use cases the emphasis should be on writing code that is easy to get right and maintain, which for C++ means using smart pointers as your default choice. I say this as someone who started programming in assembler in the 1970's and is still doing so today in C++. Counting instruction cycles was fun, but nowadays having the luxury of normally not having to worry about it is a massive productivity gain.

Maybe you're advocating for Rust, but in C++ you can of course always fall back to raw pointers for efficiency, while retaining well defined (e.g. class/scope based) lifetimes to avoid bugs.

> in C++ you can of course always fall back to raw pointers for efficiency, while retaining well defined (e.g. class/scope based) lifetimes to avoid bugs.

This is certainly what I'd recommend wherever possible. It's OK to give Foo a reference to Bar as long as Foo is declared after Bar in some common scope, so will be destroyed first. If you find it's overly difficult to prove this relationship then you need to refactor your code or use some reference counting.

And then of course Rust actually checks the relationships for you.