Const with functor modifier object

If we consider the following method, I have the impression that barI cannot change this(i.e., an instance of it Foo).

struct Foo {
  int i;
  // var shall not modify the respective instance of Foo, thus "const"
  void bar(std::function<void(int)> func) const {
    func(3);
  } 
};

However, the following is possible:

void anothermethod() {
  Foo f;
  f.bar([&](int x){f.i = 3;}); // modify Foo.i "within" Foo::bar const. Dangerous?
}

I see that the method bardoes not "directly" change the value of iits instance, but makes it "indirectly" through the given parameter func.

So, here is my question: is it dangerous to do such things (i.e. pass a function that modifies an object into a method of the constcorresponding object)?

+4
source share
1 answer

bardidn't change iyour lambda did.

, i - . bar. bar , ( , bar ), .

, , , i . , - i. i , .

+2

All Articles