c++11 - golang-style "defer" in C++ -
this question has answer here:
i reading go language's defer statement. allows specify action take when function has ended. example, if have file pointer or resource, instead of writing free/delete every possible return path, need specify defer function once.
it looks analogue might coming c++ (what standard defer/finalizer implementation in c++?, will there standardization of scope guard/scope exit idioms?) until then, there unforeseen doing object destructor makes callback? looks destructor order local variables sane , handles exceptions well, though maybe not exiting on signals.
here sample implementation... there troubling it?
#include <iostream> #include <functional> using namespace std; class frameexittask { std::function<void()> func_; public: frameexittask(std::function<void()> func) : func_(func) { } ~frameexittask() { func_(); } frameexittask& operator=(const frameexittask&) = delete; frameexittask(const frameexittask&) = delete; }; int main() { frameexittask outer_task([](){cout << "world!";}); frameexittask inner_task([](){cout << "hello, ";}); if (1+1 == 2) return -1; frameexittask skipped_task([](){cout << "blam";}); }
output: hello, world!
this exists, , it's called scope guard. see fantastic talk: https://channel9.msdn.com/shows/going+deep/c-and-beyond-2012-andrei-alexandrescu-systematic-error-handling-in-c. lets create arbitrary callable called @ exit. newer version; developed long before go existed.
it works in general, i'm not sure mean handling exceptions. throwing exceptions function has called @ scope exit mess. reason: when exception thrown (and not caught), current scope exits. destructors run, , exception continue propagating. if 1 of destructors throws, do? have 2 live exceptions.
i suppose there ways language try deal this, it's complex. in c++, it's rare throwing destructor considered idea.
Comments
Post a Comment