nullptr
nullptr

Reputation: 353

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.
      };
  }
  // ...
};

Upvotes: 1

Views: 60

Answers (1)

Benjamin Buch
Benjamin Buch

Reputation: 6113

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
}

Upvotes: 4

Related Questions