C++ lambda capture this vs capture by reference

后端 未结 4 874
误落风尘
误落风尘 2021-01-03 19:33

If I need to generate a lambda that calls a member function, should I capture by reference or capture \'this\'? My understanding is that \'&\' captures only the variable

4条回答
  •  死守一世寂寞
    2021-01-03 20:16

    It's not a clear-cut situation where on is better than the other. Rather, the two (at least potentially) accomplish slightly different things. For example, consider code like this:

    #include 
    
        class foo { 
            int bar = 0;
        public:
            void baz() {
                int bar = 1;
                auto thing1 = [&] { bar = 2; };
                auto thing2 = [this] { this->bar = 3; };
    
                std::cout << "Before thing1: local bar: " << bar << ", this->bar: " << this->bar << "\n";    
                thing1();
                std::cout << "After thing1: local bar: " << bar << ", this->bar: " << this->bar << "\n";
                thing2();
                std::cout << "After thing2: local bar: " << bar << ", this->bar: " << this->bar << "\n";
            }
        };
    
    
    int main() { 
        foo f;
        f.baz();
    }
    

    As you can see, capturing this captures only the variables that can be referred to via this. In this case, we have a local variable that shadows an instance variable (yes, that's often a bad idea, but in this case we're using it to show part of what each does). As we see when we run the program, we get different results from capturing this vs. an implicit capture by reference:

    Before thing1: local bar: 1, this->bar: 0
    After thing1: local bar: 2, this->bar: 0
    After thing2: local bar: 2, this->bar: 3
    

    As to the specifics of capturing everything vs. only what you use: neither will capture any variable you don't use. But, since this is a pointer, capturing that one variable gives you access to everything it points at. That's not unique to this though. Capturing any pointer will give you access to whatever it points at.

提交回复
热议问题