user1095108
user1095108

Reputation: 14603

tweaking captured lambda values

I have the following situation:

int p;

[p]() {
// really complex and really long code executing outside the main thread
}

The lambda object should be instantiated in several places in my code, p being captured every time. The problem is, that the code of the lambda is rather long and depends on p and I don't want to copy&paste the same code everywhere. I am reluctant to capture by reference, as the lambda is executing in the context of a thread and the referenced object may change. What would be the best thing to do? Could capturing a thread_local variable by reference help in some way?

EDIT:

in the end I went like this:

::std::function<void(int)> f; // captures the lambda

int p;

run_in_thread(::std::bind(f, p));

The reason why I didn't think of this before, was a discussion about the superiority of lambdas over ::std::bind, but apparently they are not for all purposes.

Upvotes: 0

Views: 120

Answers (1)

Tafuri
Tafuri

Reputation: 468

If you want clean code you should generally avoid lambdas with large bodies. So the cleanest solution is probably to move your code into a new function which the lambda in turn calls.

void complexFunction(int p) {
  // really complex and really long code executing outside the main thread
}

void run() {
  for(int i = 0; i < 10; ++i)
    runThread([i]() {complexFunction(i);});
}

Upvotes: 4

Related Questions