为什么for_each + lambda触发器-Waggregate-return警告? [英] Why does for_each + lambda trigger -Waggregate-return warning?

查看:286
本文介绍了为什么for_each + lambda触发器-Waggregate-return警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用gcc和 -Waggregate-return 标志尝试以下示例时,警告:函数调用具有聚合值 triggers:

When trying the following example with gcc and the -Waggregate-return flag the warning: function call has aggregate value triggers:

struct Element {
// ... stuff ...
}

Container<Element> elements(10);
for_each(begin(elements),end(elements),[](Element& e){

// ... modify elements ...

});

据我所知, -Waggregate-return flag如果任何返回结构或联合的函数被定义或调用,警告,因为,如果我理解正确,你可能通过返回一个足够大的对象来溢出堆栈。

As far as I could find out, the -Waggregate-return flag "Warns if any functions that return structures or unions are defined or called", because, if I understood correctly, you could potentially overflow the stack by returning a large enough object.

但是, for_each 返回 lambda类型,类型为 void 。为什么会触发警告?我错过了什么?

However, for_each returns the type of the lambda, whose type is void. Why does it trigger the warning? What have I missed? How can I improve my code?

推荐答案


为什么会触发警告?

Why does it trigger the warning?

大概,通过返回类或联合类型的任何东西来触发警告。 Lambdas有类类型, for_each 返回其函数参数,因此将触发警告。

Presumably, the warning is triggered by returning anything of class or union type. Lambdas have class type, and for_each returns its function argument, so that will trigger the warning.

begin(elements) end(elements)返回的迭代器类型可能会触发警告, 容器类型实现迭代器。

It's also possible that the iterator type returned by begin(elements) and end(elements) might trigger the warning, depending on how the Container type implements iterators.


如何改进我的代码? >

How can I improve my code?

我会禁用该警告;它不是真正地兼容惯用的C ++,因为它是很常见的从函数返回小类对象。它也会被例如 std :: map :: insert()触发,它返回一个对和许多其他标准库函数。

I'd disable that warning; it's not really compatible with idiomatic C++, since it's very common to return small class objects from a function. It would also be triggered by, for example, std::map::insert(), which returns a pair, and many other standard library functions.

这篇关于为什么for_each + lambda触发器-Waggregate-return警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆