[Solved] What does “[&]” mean in C++?


This statement uses a lambda expression.

auto updateSlack = [&](const char slack_type, const double s) {
    if (slack_type == 'e') {
        wns.early_slack = min(s, wns.early_slack);
        tns.early_slack += s;
    }
    else if (slack_type == 'l') {
        wns.late_slack = min(s, wns.late_slack);
        tns.late_slack += s;
    }
};

The compiler does two things. The first one is that the compiler defines an unnamed class that will contain function call operator that corresponds to the body of the lambda expression.

The second one is that the compiler creates an object of this class and assign it to variable updateSlack.

You can imagine this the following way

struct  
{
    auto &r1 = wns;
    auto &r2 = tns;

   void operator ()( const char slack_type, const double s ) const
   {
        if (slack_type == 'e') {
            wns.early_slack = min(s, wns.early_slack);
            tns.early_slack += s;
        }
        else if (slack_type == 'l') {
            wns.late_slack = min(s, wns.late_slack);
            tns.late_slack += s;
        }
    }
} updateSlack;

Then you can call the function call operator of the object somewhere in the program where a functional object is needed like

updateSlack( 'l', 10.10 );

solved What does “[&]” mean in C++?