Forums before death by AOL, social media and spammers... "We can't have nice things"
|    comp.lang.c++.moderated    |    Moderated discussion of C++ superhackery    |    33,346 messages    |
[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]
|    Message 32,668 of 33,346    |
|    =?windows-1252?Q?Daniel_Kr=FCgler?= to All    |
|    Re: Why is the lambda capture-default [=    |
|    21 Nov 12 21:20:20    |
   
   From: daniel.kruegler@googlemail.com   
      
   Am 21.11.2012 21:55, schrieb DeMarcus:   
   > When compiling the following with gcc 4.7.2 ...   
   >   
   > #include    
   > #include    
   >   
   > int main()   
   > {   
   > int myInt = 10;   
   >   
   > std::function fnc =   
   > [=]   
   > {   
   > myInt++; // Error here.   
   > std::cout << myInt << std::endl;   
   > };   
   >   
   > fnc();   
   >   
   > return 0;   
   > }   
   >   
   > ... I get the following error.   
   >   
   > error: increment of read-only variable ‘myInt’   
   >   
   > I don't understand why the myInt copy is read-only.   
      
   Because const functors are the mostly what people actually want to use,   
   therefore the lambda syntax (which is to great extends syntactic sugar)   
   was "optimized" for this use-case.   
      
   > Is it connected to some programming paradigm like functional programming?   
   > If so, is there a good website explaining the theory behind it?   
      
   There is no fundamental limitation for read-only lambda closures. Just   
   add "mutable" to the declarator. In your example this would mean to   
   rewrite your code as follows:   
      
   #include    
   #include    
      
   int main()   
   {   
    int myInt = 10;   
      
    std::function fnc =   
    [=] () mutable   
    {   
    myInt++; // Error here.   
    std::cout << myInt << std::endl;   
    };   
      
    fnc();   
      
    return 0;   
   }   
      
   HTH & Greetings from Bremen,   
      
   Daniel Krügler   
      
      
      
   --   
    [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
    [ comp.lang.c++.moderated. First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   
|
[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]
(c) 1994, bbs@darkrealms.ca