Hacker News new | ask | show | jobs
by saynsedit 3544 days ago
RAII in Rust comes from C++. If you're using new/delete in C++, you're doing it wrong.
3 comments

Sure, but RAII alone doesn't make resource management safe. It's the combination of RAII and lifetime checking that achieves it.
Not everything can live on the stack.

If you're not using new/delete in C++, you're probably not doing something very complicated. (And hey, that's not necessarily a bad thing!)

The resource manager (like std::vector or std::unique_ptr) can certainly live on the stack when the data it manages resides on the heap.
RAII can wrap heap-allocated data. Also bss-allocated objects are common.
Uhh... RAII is perfectly compatible with new/delete. You just have to put all new calls in the constructor and all delete calls in the destructor.
Yes Kenji... You put new/delete in constructor/destructor so that you don't have to call new/delete manually.
Oh, I misunderstood you. I thought you would write code without a single new or delete at all. So, everything is either living on the stack or using built-in allocations like vector and the like.
In modern C++ you do avoid it completely. Using things like std::make_unique<> and std::make_shared<> to allocate an object and stuff it into a smart pointer immediately.
Thanks. I always wanted to learn modern C++, but there was no such lecture at uni and in my spare time I was only able to fill the gaps partially, learning about the obvious things like the auto keyword and move constructors and the like.
Move constructors get a lot of press because they are new (and necessary for the underlying machinery of unique_ptr to work). But most people will never need to use it or know about it directly.

There are really two classes of C++ features, the basic use part which is fairly straightforward and nice to use. This is the API provided by the STL. Followed by the infrastructure stuff like templates, move semantics, SFINAE and other messy and non-obvious things. This latter part is much more complicated and still a mine field - but necessary for the STL to do what it does.

If you want to learn C++ get proficient in using the STL. The rest should only be learned once that is second nature.