Hacker News new | ask | show | jobs
by baq 2486 days ago
so how did you manage to not keep track of object lifetimes before? serious question, rust just forces you to do what c++ expects you to do, threatening undefined behavior at runtime if you don't. anecdotally i can say about myself that learning rust made me a better python programmer, of all things.
2 comments

Modern c++ makes lifetimes pretty implicit.

Default assumption: all data lives in a value type, or an STL container. The destructor/copy constructors will automatically deal with lifetimes for you.

Fallback #1: the remainder lives in a std::unique_ptr, or perhaps std::shared_ptr. The destructor/copy constructors will deal with lifetimes for you.

Fallback #2: Take a moment to reflect upon the mistakes that you've made that have led you here. This is your fault. Write a class with correct constructor, destructor, copy constructor, move constructor, and move/copy assignment operators. This is roughly the equivalent of resorting to unsafe in rust in a place that makes calls to other rust code. (as opposed to a syscall or a c function call or somewhere else that it's obviously required) If you're here, it's because you fucked up.

Since c++11 had become available, I've eliminated all use of new/delete from new code that I write. I've slowly refactored old code (by myself and others) to do the same. The only significant attention I've paid to lifetimes is when I'm using a c library or am writing c# where half my objects are IDisposable. (yes, really, I do more manual memory management in a garbage collected language)

The problem with c++ isn't that you have to worry about lifetimes, it's that you used to have to worry about object lifetimes and many codebases were written during that time. Sure, we could rewrite the world in rust and all of that would go away, or we could rewrite the world in modern c++ and it would also go away.

I think you missed the point of Rust. It's not about replacing new/delete with RAII (even though that's a good idea for sure). How does modern C++ help you with tracking whether a pointer/reference outlives the lifetime of the pointee? Not at all.
By using the lifetime static analysis recently introduced in clang tidy and Visual C++ 2019.

It is still in the early stages and work is being done to make it a common feature across major compiler, while improving their capabilities.

RAII, STL data structures, smart pointers, warnings as errors, static analysis as errors, and refusing to write C in C++.