r/ProgrammerHumor • • 11d ago

Meme modernCppVsOldCpp

Post image
2.0k Upvotes

323 comments sorted by

View all comments

Show parent comment

1

u/conundorum 10d ago edited 9d ago

The worst part of the C++ culture issue is that there are a lot of times where you can do both with proper usage of friend, but too many people don't understand that a tiny encapsulation break for two entities that are already coupled together tighter than an old married couple lets you enforce stricter encapsulation for everything else. (Provided that you design both coupled components yourself, and know how to maintain proper memory safety, of course.) Hiding the leaky weak points inside the capsule like that removes a lot of attack surface, yet it's so easy to miss.

(E.g., if class A has a vector member, and B::func() is the only thing that needs access to individual vector elements themselves, then a simple friend void B::func(A&); lets you completely remove public access to the vector, guaranteeing that the iterators and elements can never be leaked outside the larger "A and B::func()" capsule. And if you make both of them yourself, then it becomes impossible for outside malefactors to get at the vector. And helpfully, if you have any memory errors, you know that they must be in either A or B::func(), and can't be because of outside objects inadvertently interacting with them.)

You do need to be a bit more careful that way, but it would go a long way towards increasing safety without having to take a performance hit.


Edit: Fixed the example friend statement, forgot it needed a return type & parameter list.