简体   繁体   中英

Wrong gcc behaviour with lambda

By compiling this:

#include <iostream>
#include <sstream>

std::string makeList (std::string sep)
{
    auto makeItem = [&] (std::string item)
    {
        static char count = '0';
        return (++count, count) + sep + item + '\n';
    };

    return makeItem ("first") + makeItem ("second") + makeItem ("third");
}

int main() 
{
    std::cout << makeList (". ");
}

with gcc (5.4.0, c++11 flag) the output is this:

3. first
2. second
1. third

while the correct output, which clang (3.8, c++11 flag) gets, is:

1. first
2. second
3. third

Is there a particular reason for this behaviour?

According to cppreference :

Order of evaluation of the operands of almost all C++ operators (including the order of evaluation of function arguments in a function-call expression and the order of evaluation of the subexpressions within any expression) is unspecified. The compiler can evaluate operands in any order, and may choose another order when the same expression is evaluated again.

There is no right or wrong here, GCC evaluates right-to-left and clang left-to-right

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM