Thread: c++11 lambda question

  1. #1
    -bleh-
    Join Date
    Aug 2010
    Location
    somewhere in this universe
    Posts
    463

    c++11 lambda question

    I would like some clarification on lambda.

    In the code below, I thought that using "mutable" will let me modify the captured variables. But the lambda function f2() doesn't seem to work that way.

    Is the code below wrong? If it does, shouldn't there be a compile error?

    Code:
        int x = 1;
        int y = 50;
        int z = 3;
        auto f2 = [=] () mutable {++x ;return x+y+z;};
    
        std::cout << "f2() = " << f2() << std::endl; // print 55
        std::cout << "x = " << x << std::endl;        // print 1
    "All that we see or seem
    Is but a dream within a dream." - Poe

  2. #2
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    O_o

    The `mutable' allows you to mutate variables, but you aren't passing those variables by reference.

    Soma
    “Salem Was Wrong!” -- Pedant Necromancer
    “Four isn't random!” -- Gibbering Mouther

  3. #3
    -bleh-
    Join Date
    Aug 2010
    Location
    somewhere in this universe
    Posts
    463
    Thanks for clarifying. I misunderstood the purpose of mutable. I thought that using mutable would allow me to modify the variable outside of the lambda scope without having to pass the references.
    "All that we see or seem
    Is but a dream within a dream." - Poe

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Lambda's - What does this mean?
    By Alpo in forum C++ Programming
    Replies: 2
    Last Post: 10-19-2014, 10:42 PM
  2. Using a lambda as an encapsulated sub-function : yay or nay?
    By MutantJohn in forum C++ Programming
    Replies: 4
    Last Post: 03-07-2014, 10:42 AM
  3. Lambda captures are inefficient?
    By brewbuck in forum C++ Programming
    Replies: 6
    Last Post: 09-20-2012, 09:56 PM
  4. c++ equivalent of c# delegate/lambda
    By duck_lee in forum C++ Programming
    Replies: 1
    Last Post: 05-03-2010, 10:56 AM
  5. Lambda functions in C?
    By black0ut in forum C Programming
    Replies: 2
    Last Post: 08-12-2009, 01:26 PM