C++0x lambda capture by value always const?

Zac picture Zac · May 14, 2010 · Viewed 18.4k times · Source

Is there any way to capture by value, and make the captured value non-const? I have a library functor that I would like to capture & call a method that is non-const but should be.

The following doesn't compile but making foo::operator() const fixes it.

struct foo
{
  bool operator () ( const bool & a )
  {
    return a;
  }
};


int _tmain(int argc, _TCHAR* argv[])
{
  foo afoo;

  auto bar = [=] () -> bool
    {
      afoo(true);
    };

  return 0;
}

Answer

Edward Strange picture Edward Strange · May 14, 2010

Use mutable.


auto bar = [=] () mutable -> bool ....

Without mutable you are declaring the operator () of the lambda object const.