Home > front end >  Why does capturing by value in lambda work although object is deleted?
Why does capturing by value in lambda work although object is deleted?

Time:08-24

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.

CodePudding user response:

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.

  • Related