Google interview question

How would you implement the try/finally construct in C++?

Interview Answers

Anonymous

Feb 15, 2014

This was both difficult and unexpected because I was not expecting questions in C++, and was interviewing in Java, but I made the mistake of leaving C++ on my resume from years before.

Anonymous

Nov 1, 2014

I'm guessing this goes to using the language's built in object destruction to your advantage. So try...finally means you run some code which may fail (you can check for errors) but regardless of error status you'd always want to run the finally block. The finally block could be implemented using an object which receives a function pointer (e.g. cleanup code) upon construction, and runs that code upon destruction. i.e. since the destructor is guaranteed to be called when the function exits, the function pointer will always be called.

Anonymous

May 17, 2015

Mimicking try-finally in C++ sounds like something one shouldn't have to do if the program would follow the RAII paradigm to begin with. try/finally is an alien concept to C++ and was omitted for a reason. (But then again, programmers don't follow the RAII paradigm and may therefore have a need for try-finally.)