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: class Buffer {
franta-hg@0: private:
franta-hg@0: Buffer(const Buffer&) = delete;
franta-hg@0: Buffer& operator=(const Buffer&) = delete;
franta-hg@0: public:
franta-hg@0: size_t size;
franta-hg@0: void* data;
franta-hg@0:
franta-hg@0: Buffer(size_t size) : size(size), data(malloc(size)) {
franta-hg@0: std::cout << " allocated memory at: " << data << std::endl;
franta-hg@0: }
franta-hg@0:
franta-hg@0: virtual ~Buffer() {
franta-hg@0: free(data);
franta-hg@0: std::cout << " freed memory at: " << 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: Buffer buf(486);
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";
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: }