franta-hg@2: /**
franta-hg@2: * cpp-finally
franta-hg@2: * Copyright © 2024 František Kučera (Frantovo.cz, GlobalCode.info)
franta-hg@2: *
franta-hg@2: * This program is free software: you can redistribute it and/or modify
franta-hg@2: * it under the terms of the GNU General Public License as published by
franta-hg@2: * the Free Software Foundation, version 3 of the License.
franta-hg@2: *
franta-hg@2: * This program is distributed in the hope that it will be useful,
franta-hg@2: * but WITHOUT ANY WARRANTY; without even the implied warranty of
franta-hg@2: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
franta-hg@2: * GNU General Public License for more details.
franta-hg@2: *
franta-hg@2: * You should have received a copy of the GNU General Public License
franta-hg@2: * along with this program. If not, see .
franta-hg@2: */
franta-hg@2:
franta-hg@2: #include
franta-hg@2: #include
franta-hg@2: #include
franta-hg@2:
franta-hg@2: class Finally {
franta-hg@2: private:
franta-hg@2: Finally(const Finally&) = delete;
franta-hg@2: Finally& operator=(const Finally&) = delete;
franta-hg@2: public:
franta-hg@2: std::function fx;
franta-hg@2:
franta-hg@2: Finally(std::function fx) : fx(fx) {
franta-hg@2: }
franta-hg@2:
franta-hg@2: virtual ~Finally() {
franta-hg@2: fx();
franta-hg@2: }
franta-hg@2: };
franta-hg@2:
franta-hg@2: void fxThrowing(bool fail, void* data) {
franta-hg@2: std::cout << " doing something with data " << data << std::endl;
franta-hg@2: if (fail) throw std::logic_error("error from fxThrowing()");
franta-hg@2: }
franta-hg@2:
franta-hg@2: void fxAllocating(bool fail) {
franta-hg@2: void* buf = malloc(486);
franta-hg@2: void* tmp = malloc(123);
franta-hg@2: std::cout << " allocated memory at: " << buf << std::endl;
franta-hg@2: std::cout << " allocated memory at: " << tmp << std::endl;
franta-hg@2:
franta-hg@2: Finally finally([&]() {
franta-hg@2: free(buf);
franta-hg@2: free(tmp);
franta-hg@2: std::cout << " freed memory at: " << buf << std::endl;
franta-hg@2: std::cout << " freed memory at: " << tmp << std::endl;
franta-hg@2: });
franta-hg@2:
franta-hg@2: fxThrowing(fail, buf);
franta-hg@2: fxThrowing(fail, tmp);
franta-hg@2: }
franta-hg@2:
franta-hg@2: int main(int argc, char** argv) {
franta-hg@2: bool fail = argc == 2 && std::string("fail") == argv[1];
franta-hg@2: const char* name = "good-lambda";
franta-hg@2: std::cout << name << " (fail=" << fail << ")\n";
franta-hg@2: try {
franta-hg@2: fxAllocating(fail);
franta-hg@2: } catch (const std::exception& e) {
franta-hg@2: std::cout << " caught exception: " << e.what() << std::endl;
franta-hg@2: }
franta-hg@2: }