News for hackers. Stuff that matters.
Re:Ask HN: Good C++ code bases to read? by gumby on Wednesday October 28, 2020 @01:29PM (#24921617)
what if you allocate on the stack?

    {
      something a_thing {};
      ...;
    }
Is a perfectly reasonable way to allocate something on the stack and have it unwound at the end of the block. No pointers needed. Perhaps I'm misunderstanding your argument.

`new`, much less `malloc` hardly ever need appear. I'm working in a reasonably large code base that has four uses of new: three hidden in in internal graph node construction and one in a high-performance deserializer (actually that last is in the process of being replaced by code that simply requests pages from the OS). There are very few cases where user code might allocate memory with `new` these days.

pooya13's argument stands as well.

Re:Ask HN: Good C++ code bases to read? by thechao on Wednesday October 28, 2020 @01:45PM (#24921822)
unique_ptr<> is a mechanism to give automatic (this is what you mean by 'on the stack') life time to non-automatic objects, like FILE*s, mmap()s, defined results from malloc(), etc. It's not like I'm heap-allocating an int for local use.
Re:Ask HN: Good C++ code bases to read? by gumby on Wednesday October 28, 2020 @04:13PM (#24923599)
IMHO that's a painful level of abstraction to work at.

Yes, 'automatic' variables in C or C++ are just stack allocated objects;, there's nothing about a FILE* that makes it automatic or static. But if you use, for example, streams you can just create one for a file and when it goes out of scope it closes the file and deallocates for you.

Likewise I would make a tiny class for my mmap'ed memory that did whatever cleanup (perhaps searializing data or zeroing pointers into it) before returning the pages to the OS pool. Sure you can write that code into a unique_ptr deleter and pass that in when you make them, or you could just let the compiler do it for you.

I don't use C++ in what would typically be called an "object-oriented" way, but this is a perfect example of where I would create a small class as a way of telling the compiler to do some bookkeeping on my behalf.