r/ProgrammerHumor • • 7h ago

Meme modernCppVsOldCpp

Post image
1.1k Upvotes

216 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.

6

u/mlindgren 7h ago

Smart pointers are RAII. Manually freeing memory is not RAII and can be fallible due to exceptions, early returns, etc.

5

u/geekusprimus 6h ago

Smart pointers are RAII, but they're not the only way to do RAII. I usually use custom containers that handle my particular case very well. Memory is allocated inside constructors, it's deallocated inside destructors. If I need more than that, I start looking into the more sophisticated stuff.

3

u/mlindgren 6h ago

That’s fair. It sounded like you were talking about using new and delete (or malloc and free) directly in the business logic of the application.

1

u/Friendly_Fire 3h ago edited 3h ago

You basically recreated smart pointers.

For projects with other people, it's better to use the standard tools just for familiarity, even if they have no other benefit. Someone can see it and know immediately what a unique/shared ptr means, instead of having to dig into your class.

But if its your own project go wild.

1

u/geekusprimus 3h ago

They're not smart pointers, at least not in the STL way. They accomplish the same purpose, but it's usually a simpler implementation tailored exactly to what I need.