Can you capture arrays in a lambda?

随声附和 提交于 2021-02-08 12:19:35

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/15423695/can-you-capture-arrays-in-a-lambda

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!