Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does const lambda mean?

#include <iostream>
int foo(int i)
{
    const auto a = [&i](){ i = 7; return i * i; };
    a();
    return i;
}
int main()
{
    std::cout << foo(42) << std::endl;
    return 0;
}

This compiles( g++ -std=c++11 -Wall -Wextra -Wpedantic main.cpp ) and returns 49. Which is surprising to me, because by declaring a to be a constant object, I would have expected i to be referenced as const int&. It clearly isn't, why?

like image 775
Vorac Avatar asked Oct 14 '16 11:10

Vorac


People also ask

How to const int i in a lambda function?

When you capure iit is captured as the type it is. So internally it has a int&. A const before the variable declaration of the closure does not change anything for the lambda. You have 2 options to solve this: const int i = 5; auto b = [&i]() { i++; }; //error on i++

What is the Lambda in physics?

In physics, lambda λ λ λ is mainly used as a variable to denote or indicate the wavelength of any wave. In nuclear physics and radioactivity, lambda is used to indicate the radioactivity decay constant. In terms of electric fields, then lambda is also used to indicate the linear charge density of a uniform line of electric charge.

How do you pronounce the letter lambda?

The ancient grammarians and dramatists give evidence to the pronunciation as [laːbdaː] ( λάβδα) in Classical Greek times. In Modern Greek, the name of the letter, Λάμδα, is pronounced [ˈlam.ða] . In early Greek alphabets, the shape and orientation of lambda varied.

What is Lambda in the Poisson distribution?

In the Poisson distribution formula, lambda (λ) is the mean number of events within a given interval of time or space. For example, λ = 0.748 floods per year. What are the main assumptions of statistical tests?


1 Answers

[&i](){ i = 7; return i * i; }

is mainly equivalent to

class Lambda
{
public:
    Lambda(int& arg_i) : i(arg_i) {}

    auto operator() () const { i = 7; return i * i;}
private:
    int& i;
};

And so then you have:

const Lambda a(i);
a();

And the const Lambda won't promote its member to const int& i; but int& const i; which is equivalent to int& i;.

like image 191
Jarod42 Avatar answered Sep 17 '22 05:09

Jarod42