c++functional-programmingmonadsmonad-transformerscombinators

How C++ lambda move capture *this in rvalue reference member function?


we can move capture variable in c++ as follow.

string s;
auto f = [s = std::move(s)](){ /* do something */ };

we can copy capture this as follow.

auto f = [*this](){ /* do something */ };

but how can we move capture this in rvalue reference member function?

class Obj {
  // ...
  auto method() && {
      // do something.
      return [ /* "*this = std::move(*this)" is a syntax error */ ](){
        // do something.
      };
  }
  // ...
};

Solution

  • You can normally assign it to a variable. ;-)

    class Obj {
      // ...
      auto method() && {
          // do something.
          return [self = std::move(*this)](){
            // Use self.member here
          };
      }
      // ...
    };
    

    Note that the type of self is const Obj. If you want it to be non const, you have to make the lambda mutable.

    [self = std::move(*this)]()mutable{
        // Use self.member here
    }