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