Hacker News new | ask | show | jobs
by nitnelave 809 days ago
If you want an instance with a destructor (e.g. print "this was called X times"), you need a class.
1 comments

That example seems contrived. Why would I want to know something was called n-times? Even for benchmarking I would just capture an integer and increment it.

To be mildly pedantic, printing in a destructor is horrible practice because stdout/stderr might be pipes or sockets and writing might fail. It's a really bad idea to do anything in a destructor that effects anything but the class being destroyed for those reasons, and when you get an error, it shows up as an opaque exception or trace or hang at the end of a scope instead of where it actually mattered.

I actually ran into that at work a few days ago. I wanted to provide a callback that accumulated stuff, and check that the total was equal to what was expected, or crash the program otherwise (fail fast). I could have equivalently written the output of the test to a capture-by-ref variable and checked it outside if I really wanted to.