Hacker News new | ask | show | jobs
by SideQuark 36 days ago
> where the programmer is responsible for invoking "free", was a serious mistake and it was an obsolete technique already at the date of its introduction.

It wasn’t obsolete then nor now. Garbage collected languages, to this day, still use on average about 2x-5x the working memory of carefully written manual memory programs. A significant amount of devices then and even today cannot support such sloppy use of resources.

2 comments

I think they mean something more akin to RAII in C++/rust. Manually writing a free statement is very error-prone and there are better language-level features to avoid that.
RAII has nothing to do with garbage collection. It only provides a way to get a resource somewhat atomically. If the creator doesn’t delete the object, or if the object has a malformed destructor, it fails. If the creator calls delete twice, it fails. There’s really no garbage collection at all here.
Is there a scheme where memory is auto-freed if it goes out of scope?

If so, are there benefits/drawbacks to that?

If it's on the stack, it's almost free to do.

If it's held by a unique_ptr, then it auto frees, but there is a lot of programmer work to ensure things behave well, and there are nuances to allocating something into the unique_ptr.

If it's a std::shared_ptr, which is the closest to what people think of, it's then a reference counted object, which requires a little more storage, and also has the ability to be mishandled as a pointer, screwing it up, or making the wrong type of copy of the shared_ptr, so two there are two things, and also fails to release object in the case of circluar references.

Then there's a lot of other subtle things you can do, and none of this is as lightweight as a pointer, and none is as automatic as what most people think of as garbage collection.

And each has costs and tradeoffs, which is why C++ added them: making certain tradeoffs easier to use, but it requires solid understanding of how such things work.