简体   繁体   中英

gcc >=10.1 and clang do not detect unused but set lambda

Consider the following program:

template <unsigned int I>
int f(int x)
{
    auto task = [&]() { ++x; };
    if constexpr (I == 0) {
        task();
    }
    return x;
}

int main()
{
    f<1>(3);
}

Compiling on gcc 9.3 with -std=c++17 -Wall -pedantic , it issues a warning

warning: variable 'task' set but not used [-Wunused-but-set-variable]
    4 |     auto task = [&]() { ++x; };

But with a newer gcc version, no such warning appears. Notice that according to the manual , -Wunused-but-set-variable is enabled by -Wall .

Also with clang, no such a warning appears.

Test it on godbolt .

Is that a compiler shortcoming, or is this behavior (the lack of warning) wanted/expected?

Consider this slightly modifed code:

template <unsigned int I>
int f(int x)
{
    auto task = [&]() { ++x; };
    if constexpr (I == 0) {
        task();
    }
    return x;
}

int main()
{
    f<0>(3);
    f<1>(3);
}

With gcc 9.3 -std=c++2a -Wall -Werror you get an error (warning treated as error) :

<source>: In instantiation of 'int f(int) [with unsigned int I = 1]':
<source>:14:11:   required from here
<source>:4:10: error: variable 'task' set but not used [-Werror=unused-but-set-variable]
    4 |     auto task = [&]() { ++x; };
      |          ^~~~
cc1plus: all warnings being treated as errors

This is bad, because the code is completely fine and it can be considered a bug that it triggers a warning. Apparently this has been fixed in gcc >= 10.1.

One could argue that one could/should move declaration of task into the if constexpr branch, but then consider that this made gcc issue a warning as well:

template <unsigned int I>
int f(int x)
{
    auto task = [&]() { ++x; };
    if constexpr (I == 0) {
        task();
    } else if constexpr (I == 1) {
        task();
    } 
    return x;
}

int main()
{
    f<0>(3);
    f<1>(3);
    f<2>(3);
}

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