Allow for mutable lambdas with Future::ensure()
authorJason Rahman <jprahman@fb.com>
Tue, 28 Jul 2015 06:48:48 +0000 (23:48 -0700)
committerfacebook-github-bot-4 <folly-bot@fb.com>
Tue, 28 Jul 2015 07:22:12 +0000 (00:22 -0700)
Summary: Update the internal lambda to mutable to support mutable lambdas as
parameters to Future::ensure()

Reviewed By: @yfeldblum

Differential Revision: D2286097

folly/futures/Future-inl.h
folly/futures/test/EnsureTest.cpp

index 0756fd34423f6e5a8e54ab1f3f978f4bb33884b4..d4614fce2e8bc50dd4098d364b57ef7984369250 100644 (file)
@@ -301,7 +301,7 @@ template <class T>
 template <class F>
 Future<T> Future<T>::ensure(F func) {
   MoveWrapper<F> funcw(std::move(func));
-  return this->then([funcw](Try<T>&& t) {
+  return this->then([funcw](Try<T>&& t) mutable {
     (*funcw)();
     return makeFuture(std::move(t));
   });
index b3fa6b0cc302d6906d66c96685a50c6836508fc5..99ed4602fc67081248ee4872895f6dc779c8e50f 100644 (file)
  * limitations under the License.
  */
 
+#include <memory>
+#include <unordered_set>
+
 #include <gtest/gtest.h>
 
+#include <folly/MoveWrapper.h>
 #include <folly/futures/Future.h>
 
 using namespace folly;
 
 TEST(Ensure, basic) {
   size_t count = 0;
-  auto cob = [&]{ count++; };
+  auto cob = [&] { count++; };
   auto f = makeFuture(42)
     .ensure(cob)
     .then([](int) { throw std::runtime_error("ensure"); })
@@ -31,3 +35,16 @@ TEST(Ensure, basic) {
   EXPECT_THROW(f.get(), std::runtime_error);
   EXPECT_EQ(2, count);
 }
+
+TEST(Ensure, mutableLambda) {
+  auto set = std::make_shared<std::unordered_set<int>>();
+  set->insert(1);
+  set->insert(2);
+
+  auto f = makeFuture(4)
+    .ensure([set]() mutable { set->clear(); })
+    .then([]() { throw std::runtime_error("ensure"); });
+
+  EXPECT_EQ(0, set->size());
+  EXPECT_THROW(f.get(), std::runtime_error);
+}