locked
Using value class with for_each RRS feed

  • Question

  • When attempting to update an instance of a value class defined outside of a for_each call from the lambda expression in the for_each call the compiler returns error C3490 stating that the members of the instance cannot be modified as they are being accessed through a const object. The members of the instance can be readily modified by code outside of the for_each call. Is there a problem with value classes in this context??

    Some example code:

     

    Size mysize;

    std::for_each(begin(mylist), end(mylist),

    [mysize](childType^ child) { mysize.Width = 10.0; } );

    Monday, October 24, 2011 6:14 PM

Answers

All replies

  • Add a mutable in there.

    for_each(begin(mylist), end(mylist),
     [mysize](Size child) mutable { mysize.Width = 10.0; } );


    http://blog.voidnish.com
    Monday, October 24, 2011 8:36 PM
  • Many thanks. I must confess that I was not fully aware of the subtle details of the C++ lambda expression syntax. However, it is interesting that lambda expressions capture variables passed by value as const by default. Comparing this to a simple function definition with arguments passed by value where the default is not const unless explicitly stated.
    Friday, October 28, 2011 8:50 PM
  • Many thanks. I must confess that I was not fully aware of the subtle details of the C++ lambda expression syntax. However, it is interesting that lambda expressions capture variables passed by value as const by default. Comparing this to a simple function definition with arguments passed by value where the default is not const unless explicitly stated.

    Well that's the same with lambdas too. Parameters passed to the lambda function are not const by default, it's captured variables that are const by default. Functions do not have the concept of capturing variables, so there is no real comparable there.
    http://blog.voidnish.com
    Friday, October 28, 2011 10:25 PM