Barry
Barry

Reputation: 303537

Can you capture arrays in a lambda?

I'm in a situation in a multithreaded environment where I have a thread that receives data from a socket, and I want to send that data into a messaging queue.

For instance, something like this:

char buf[N];
size_t len = ::recv(buf, ...);
queue.send([buf,len] {
    //stuff
});

But that won't work since buf could go out of scope, or get overwritten by the next ::recv(). Now I COULD copy it into a string/std::vector/whatever and pass THAT thing by value:

char buf[N];
size_t len = ::recv(buf, ...);
std::string my_data(buf, len);
queue.send([my_data](){ /* stuff */ });

But there I'm incurring an extra copy, right? Is there a way to get that same functionality without the extra overhead?

Upvotes: 17

Views: 8678

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283803

Yes, you can. The Standard says that (5.1.2p21):

When the lambda-expression is evaluated, the entities that are captured by copy are used to direct-initialize each corresponding non-static data member of the resulting closure object. (For array members, the array elements are direct-initialized in increasing subscript order.)

which makes it clear that a lambda can capture an array by copy.

Upvotes: 24

Related Questions