At work, I'm used to exceptions with the try-catch-finally format. I wondered how to add 'finally' to C++.
After seeing a finally block wasn't implemented in C++11 (Stroustrup is against them in favor of RAII...), and how others asked for it, I tried this alternative. I think it does the trick without any issue, as finally is used to clean up any resources allocated in the try block. I think it's nice to have. Do you think this alternative is just as effective?
1) Put this at the top of your code: #define finally
2) And, since you can create a unit block using { }, just put finally before that.
Example (poor, but proves a point):
#define finally#include using namespace std;int main(){ int *p = NULL; try { cout << "Allocating..." << endl; p = new int; } catch(bad_alloc e) { cout << e.what() << endl; } finally { cout << "Cleaning up!" << endl; delete p; } return 0;}
Output:
Allocating...
Cleaning up!