116

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;
}
Zac
  • 3,235
  • 4
  • 25
  • 30

2 Answers2

194

Use mutable.


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

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

Edward Strange
  • 40,307
  • 7
  • 73
  • 125
-6

There is alternative way to using mutable (solution proposed by Crazy Eddie).

With [=] your block captures all objects by values. You can use [&] to capture all objects by reference:

auto bar = [&] () -> bool

Or you can capture by reference only certain object [=, &afoo]:

auto bar = [=, &afoo] () -> bool

Refer to this page for fore details (Explanation section): http://en.cppreference.com/w/cpp/language/lambda

Vlad
  • 1,631
  • 1
  • 16
  • 21
  • 15
    This does completely different things. They are not interchangeable. This doesn't respond to the OP's question. – Edward Strange Nov 08 '16 at 01:21
  • 2
    The problem of this solution is that it does not work for captured local variables destroyed before the lambda is executed (for example, when you start a detached std::thread). – Simon Ninon Sep 13 '17 at 02:08