您可以在lambda中捕获数组吗? [英] 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.
例如,像这样的东西:
char buf[N];
size_t len = ::recv(buf, ...);
queue.send([buf,len] {
//stuff
});
但是这将不起作用,因为buf
可能超出范围,或者被下一个::recv()
覆盖.现在,我可以将其复制到string
/std::vector
/任何文件中,然后按值传递那个东西:
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?
推荐答案
是的,可以.标准说(5.1.2p21):
Yes, you can. The Standard says that (5.1.2p21):
当评估lambda表达式时,通过复制捕获的实体将用于直接初始化结果闭包对象的每个对应的非静态数据成员. (对于数组成员,数组元素以递增的下标顺序直接初始化.)
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.)
这很清楚,lambda可以通过副本捕获数组.
which makes it clear that a lambda can capture an array by copy.
这篇关于您可以在lambda中捕获数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!