Hacker News new | ask | show | jobs
by angersock 5287 days ago
So, all we're going to do is nerdrage about C vs. C++ here. There will be diehard architecture astronauts on the one side, and crufty neckbeards on the other. We've all seen this thread before.

~

Instead, let's talk about things that C++ got right that aren't super obvious! :)

For me, one of the coolest things about C++ is having destructors. The neat thing about them is that they are based on the scope of an object, and tie directly into when the object leaves scope in the language (as determined at compile time). Any code there gets run when the object is deleted or leaves scope, and this is guaranteed to happen immediately.

So, I know exactly when an object is no longer "needed", and if I'm careful I can use things like smart pointers and reference counting to guarantee that a shared resource gets removed when it needs to. I can also override new/delete and do some magic to have a reliable "hey, come free me from the heap later" behavior--when the destructor is called, have the class append itself to a list of things to be GC'ed when the time is right.

Java, for example, doesn't do this--a request to finalize may be fulfilled, one day, when the VM feels like it. This makes smart handling of things like system resources really clunky, and can force me to write C-ish code like freeSystemResources() or something. Having an ability to explicitly know when lexical scope has been left is pretty cool.

What other cool things have you seen in C++ (or C)?