From 020ddc40c5d807513b01767dace2e607ceae9055 Mon Sep 17 00:00:00 2001 From: Herb Sutter Date: Wed, 24 Feb 2021 16:49:57 -0800 Subject: [PATCH] Fine, make it move-constructible (only) To satisfy some compilers. And might as well reinstate that test case. --- include/gsl/util | 10 ++++++++-- tests/utils_tests.cpp | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/include/gsl/util b/include/gsl/util index ebaeef6..5e9256f 100644 --- a/include/gsl/util +++ b/include/gsl/util @@ -52,14 +52,20 @@ template class final_action { public: - explicit final_action(F f_) : f(f_) { } - ~final_action() { f(); } + explicit final_action(F f_) : f(std::move(f_)) { } + ~final_action() { if (invoke) f(); } + + final_action(final_action&& other) + : f(std::move(other.f)), invoke(std::exchange(other.invoke, false)) + { } final_action(const final_action& rhs) = delete; final_action& operator=(const final_action&) = delete; + final_action& operator=(final_action&& other) = delete; private: F f; + bool invoke = true; }; // finally() - convenience function to generate a final_action diff --git a/tests/utils_tests.cpp b/tests/utils_tests.cpp index 705f384..74dc990 100644 --- a/tests/utils_tests.cpp +++ b/tests/utils_tests.cpp @@ -51,6 +51,25 @@ TEST(utils_tests, finally_lambda) EXPECT_TRUE(i == 1); } +TEST(utils_tests, finally_lambda_move) +{ + int i = 0; + { + auto _1 = finally([&]() { f(i); }); + { + auto _2 = std::move(_1); + EXPECT_TRUE(i == 0); + } + EXPECT_TRUE(i == 1); + { + auto _2 = std::move(_1); + EXPECT_TRUE(i == 1); + } + EXPECT_TRUE(i == 1); + } + EXPECT_TRUE(i == 1); +} + TEST(utils_tests, finally_const_lvalue_lambda) { int i = 0;