mardi 23 juin 2015

const static auto lambda used with capture by reference

While using some local lambda objects in a C++11 function I was tempted to declare them as const static auto lambda = ... just to let the compiler know that there is just one std::function object needed (and possibly optimize the call and/or inline it) but I realized that capturing local values by reference in this circumstance leads to weird behavior.

Consider the following code:

void process(const Data& data, const std::function<void(DataElement&>& lambda) {
  ...
}

void SomeClass::doSomething()
{
  int foo = 0;

  const static auto lambda = [&foo] () { .... ++foo; .... }

  process(data, lambda);
}

This doesn't work with multiple invocations of doSomething() but the mechanics is not clear.

  • Is foo bound at the first invocation and then kept bound to a stack address which becomes invalid on successive invocations?
  • Am I forced so drop static in this circumstance?

Where is this behavior specified in the standard? Considering it's a static variable where is it constructed? Lazily on first invocation of doSomething() (so that the first invocation works) or at program start?

Aucun commentaire:

Enregistrer un commentaire