1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/good-lambda.cpp Wed Oct 30 22:08:49 2024 +0100
1.3 @@ -0,0 +1,68 @@
1.4 +/**
1.5 + * cpp-finally
1.6 + * Copyright © 2024 František Kučera (Frantovo.cz, GlobalCode.info)
1.7 + *
1.8 + * This program is free software: you can redistribute it and/or modify
1.9 + * it under the terms of the GNU General Public License as published by
1.10 + * the Free Software Foundation, version 3 of the License.
1.11 + *
1.12 + * This program is distributed in the hope that it will be useful,
1.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
1.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1.15 + * GNU General Public License for more details.
1.16 + *
1.17 + * You should have received a copy of the GNU General Public License
1.18 + * along with this program. If not, see <http://www.gnu.org/licenses/>.
1.19 + */
1.20 +
1.21 +#include <iostream>
1.22 +#include <exception>
1.23 +#include <functional>
1.24 +
1.25 +class Finally {
1.26 +private:
1.27 + Finally(const Finally&) = delete;
1.28 + Finally& operator=(const Finally&) = delete;
1.29 +public:
1.30 + std::function<void(void) > fx;
1.31 +
1.32 + Finally(std::function<void(void) > fx) : fx(fx) {
1.33 + }
1.34 +
1.35 + virtual ~Finally() {
1.36 + fx();
1.37 + }
1.38 +};
1.39 +
1.40 +void fxThrowing(bool fail, void* data) {
1.41 + std::cout << " doing something with data " << data << std::endl;
1.42 + if (fail) throw std::logic_error("error from fxThrowing()");
1.43 +}
1.44 +
1.45 +void fxAllocating(bool fail) {
1.46 + void* buf = malloc(486);
1.47 + void* tmp = malloc(123);
1.48 + std::cout << " allocated memory at: " << buf << std::endl;
1.49 + std::cout << " allocated memory at: " << tmp << std::endl;
1.50 +
1.51 + Finally finally([&]() {
1.52 + free(buf);
1.53 + free(tmp);
1.54 + std::cout << " freed memory at: " << buf << std::endl;
1.55 + std::cout << " freed memory at: " << tmp << std::endl;
1.56 + });
1.57 +
1.58 + fxThrowing(fail, buf);
1.59 + fxThrowing(fail, tmp);
1.60 +}
1.61 +
1.62 +int main(int argc, char** argv) {
1.63 + bool fail = argc == 2 && std::string("fail") == argv[1];
1.64 + const char* name = "good-lambda";
1.65 + std::cout << name << " (fail=" << fail << ")\n";
1.66 + try {
1.67 + fxAllocating(fail);
1.68 + } catch (const std::exception& e) {
1.69 + std::cout << " caught exception: " << e.what() << std::endl;
1.70 + }
1.71 +}