How do I run a cleanup code on the function exit?
问题 C++ classes provide RAII idiom. Therefore you don't have to care about exceptions: void function() { // The memory will be freed automatically on function exit std::vector<int> vector(1000); // Do some work } But if you have (for some reasons) to use some pure C API, you have either to create C++ wrappers around it or to use try/catch blocks void function() { int *arr = (int*)malloc(1000*sizeof(int)); if (!arr) { throw "cannot malloc"; } try { // Do some work } catch (...) { free(arr); //