简体   繁体   中英

Why does capturing by value in lambda work although object is deleted?

Why does this code work?

// Online C compiler to run C program online
#include <cstdio>
#include <vector>
#include <functional>
#include <memory>
#include <iostream>

using FilterContainer = std::vector<std::function<bool(int)>>;

FilterContainer filters; 

class Widget
{
    public:
    int divisor = 0;
    void addFilter() const;
    Widget(int a):divisor(a){}
};

void Widget::addFilter() const
{
    auto divisorCopy = divisor;
    
    filters.emplace_back(
        [=](int value)
        { return value % divisorCopy == 0; }
    );
}

void doSomeWork()
{
auto pw = std::make_unique<Widget>(5); 

pw->addFilter(); 

} 

int main() {
   
   doSomeWork();
  
   std::cout<< filters[0](10);

    return 0;
}

The object widget is deleted after doSomeWork(), so why is divisor still copied succesfully in divisorCopy? When the function in filters is executed, divisor should be non-existent.

You don't capture the Widget object, you capture the local variable divisorCopy by value.

This of course creates a copy of the divisorCopy value, stored internally in the lambda object. This lambda-local copy is separate and distinct from the original divisorCopy variable.

When addFilter function returns, the lambda-local copy still lives on and can be used.

The destruction of the Widget object isn't related to what happens.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM