Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does for_each + lambda trigger -Waggregate-return warning?

Tags:

c++

c++11

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 ...

});

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.

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?

like image 780
gnzlbg Avatar asked Jul 13 '12 15:07

gnzlbg


People also ask

Why use for_ each c++?

for_each loop in C++ Apart from the generic looping techniques, such as “for, while and do-while”, C++ in its language also allows us to use another functionality which solves the same purpose termed “for-each” loops. This loop accepts a function which executes over each of the container elements.

Why use for_ each?

The for_each loop is meant to hide the iterators (detail of how a loop is implemented) from the user code and define clear semantics on the operation: each element will be iterated exactly once.

Does C++ have foreach?

The working of foreach loops is to do something for every element rather than doing something n times. There is no foreach loop in C, but both C++ and Java have support for foreach type of loop. In C++, it was introduced in C++ 11 and Java in JDK 1.5.


1 Answers

Why does it trigger the warning?

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.

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?

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.

like image 83
Mike Seymour Avatar answered Oct 11 '22 15:10

Mike Seymour