PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 4, 2022

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

 November 04, 2022     c++, capture, lambda     No comments   

Issue

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.


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.



Answered By - Some programmer dude
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing