Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading