lundi 1 août 2022

C++11 lambda: when do we need to capture [*this] instead of [this]?

For a quick sample we could see:

class Foo {
  std::string s_; 
  int i_;
public:
  Foo(const std::string& s, int i) : s_(s), i_(i) {}
  void Print() {
    auto do_print = [this](){
      std::cout << s_ << std::endl;
      std::cout << i_ << std::endl;
    };
    do_print();
  }
};

Ok, capture [this], so the lambda do_print could use s_ and i_ member of Foo. Capture [this] is enough.

But when do we have to capture [*this] instand of [this]? What could be a typical use-case / scenario, any quick samples?

Thanks!

Aucun commentaire:

Enregistrer un commentaire