none
"A variable with static storage duration cannot be captured in a lambda" RRS feed

  • Question

  • What I'm trying to do is sort a vector based on a variable known as "result time". I have the function that will help me sort it, but I'm getting an error:

    "A variable with static storage duration cannot be captured in a lambda".

    The bolded part is where the error is showing up. I'm confused as to why this is happening. Before I added an MFC GUI to the project, this worked just fine. Does anyone know what the problem might be and how I could fix it?

    Schedule mySchedule; //declared globally at the start of the program.
    
    std::sort(taskvector2.begin(), taskvector2.end(),
    			[&mySchedule](Schedule::Tracker* schedule1, Schedule::Tracker* schedule2)
    		{
    			return mySchedule.isSmaller(schedule1->m_resulttime, schedule2->m_resulttime);
    		}
    		);

    Sunday, March 24, 2019 12:32 AM

Answers

  • Use an empty capture (i.e.,  []).  You can refer directly to your global variable in the body of the lambda.

    From Lambda Expressions in C++

    Lambda Body

    The lambda body (compound-statement in the Standard syntax) of a lambda expression can contain anything that the body of an ordinary method or function can contain. The body of both an ordinary function and a lambda expression can access these kinds of variables:

    • Captured variables from the enclosing scope, as described previously.

    • Parameters

    • Locally-declared variables

    • Class data members, when declared inside a class and this is captured

    • Any variable that has static storage duration—for example, global variables

    • Marked as answer by Danzellen Sunday, March 24, 2019 8:02 PM
    Sunday, March 24, 2019 11:05 AM

All replies

  • Just drop the capture. A lambda can use a global variable without capturing it.

    Igor Tandetnik

    Sunday, March 24, 2019 1:16 AM
  • I...thought it was necessary. How would I do it without the capture?
    Sunday, March 24, 2019 5:15 AM
  • Use an empty capture (i.e.,  []).  You can refer directly to your global variable in the body of the lambda.

    From Lambda Expressions in C++

    Lambda Body

    The lambda body (compound-statement in the Standard syntax) of a lambda expression can contain anything that the body of an ordinary method or function can contain. The body of both an ordinary function and a lambda expression can access these kinds of variables:

    • Captured variables from the enclosing scope, as described previously.

    • Parameters

    • Locally-declared variables

    • Class data members, when declared inside a class and this is captured

    • Any variable that has static storage duration—for example, global variables

    • Marked as answer by Danzellen Sunday, March 24, 2019 8:02 PM
    Sunday, March 24, 2019 11:05 AM