Why [[nodiscard]] doesn't work with a reference?

317 Views Asked by At

It looks like the attribute [[nodiscard]] doesn't work when the function returns a reference.

This code gives the expected warning:

int a;

[[nodiscard]] int get()
{
    return a;
}

int main()
{
    get();
}

However, this code compiles without any complains even with -Wall -Wextra -pedantic:

int a;

[[nodiscard]] int& get()
{
    return a;
}

int main()
{
    get();
}

The only difference between the two is that the function returns a reference in the second test.

The version of my compiler is g++ (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0.

Is this a correct behavior or a bug in the compiler? If this is deliberate, what is the reason for that?

0

There are 0 best solutions below