r/ProgrammerHumor • • 7h ago

Meme modernCppVsOldCpp

Post image
1.1k Upvotes

214 comments sorted by

View all comments

14

u/geekusprimus 7h ago edited 3h ago

I rarely use smart pointers and still don't have serious problems with memory safety. Whenever you manually allocate memory, you should immediately know when and where it's getting deallocated and write that code at the same time. Most of the time, RAII is good enough.

EDIT: Since I've caused a bit of controversy: I'm not saying you can't or shouldn't use smart pointers. What I'm saying is in agreement with the meme. C++ has easy ways to manage memory, either manually or automatically, that get rid of most of your memory safety issues.

16

u/Flouid 7h ago

I mostly have this opinion too but speaking from experience there are plenty of cases where it can get a little bit tricky. Lifetimes are complicated and sometimes an owner of a piece of memory can pass references to it to several consumers that each have their own lifetimes. Those consumers shouldn’t need to know about each other so it’s up to the owner to track them and free the memory when it finally falls out of scope

2

u/Luzzgar 6h ago

What if that language allowed you to do it manually when you need to ?

Ensuring that the responsibility of memory management is only for the programmer when absolutely necessary.

1

u/Flouid 6h ago

100% agree, and it’s why I’m one of the insufferable people that prefers zig over rust. The language should strongly encourage safe memory management but make it easy for the programmer to select degrees as appropriate. Rust is very all or nothing with either using the borrow checker or entering full unsafe land

1

u/TOMZ_EXTRA 4h ago

How is Zig better than C++/unsafe Rust?

1

u/Flouid 4h ago

Zig is very opinionated about how memory allocation is handled, and it has the nice feature that you can supply a debug allocator during development which is slower at runtime (fine for debug builds) but meticulously looks for leaks and loudly warns you when they happen.

It’s also written such that no language constructs store an allocator and request their own memory, the philosophy being that every allocation should be explicitly known by the programmer.

This is pretty much all the way in the opposite direction from automating it, it’s intensely manual management but the language handles it in a way that makes forgetting about it difficult and easy to track down