diff options
author | Herb Sutter <herb.sutter@gmail.com> | 2021-02-25 03:49:57 +0300 |
---|---|---|
committer | Herb Sutter <herb.sutter@gmail.com> | 2021-02-25 03:49:57 +0300 |
commit | 020ddc40c5d807513b01767dace2e607ceae9055 (patch) | |
tree | 8b2bc272a6d2a1ceb5774a3f7630747353f8610e | |
parent | f59cb795a0fec46f20bc66262bdbb3f05551137e (diff) |
Fine, make it move-constructible (only)
To satisfy some compilers.
And might as well reinstate that test case.
-rw-r--r-- | include/gsl/util | 10 | ||||
-rw-r--r-- | 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 F> 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; |