Monday 17 June 2019

C++ : "ignored-qualifiers" warnings are a bit wrong

It has been a while hasn't it... I'm very busy, sorry.... But here's an item, the const qualifier on return types in C++... So, I'm of the same mind as Scott Meyers that you should const everything you can whenever possible, and one place I always const is on return codes from functions where I don't want the result to be mutable, like this:

const bool OverTen(const int& p_Value)
{
return p_Value > 10;
}

I don't want the caller to this function to modify the result, that bool they get back, I want it to be constant, I want them to use that bool for that one purpose.

This compiled fine, until you compile with -Wextra, where you then get -Wignored-qualifies and the message:

warning: 'const' type qualifier on return rype has no effect

But I want it to have an effect, I want that to be immutable, it's a constant boolean.  It could be anything, a constant error code value, I don't want someone to fudge over an error by setting it to some other value!  I want it to be constant.

It not being constant allows crusty code like this:

auto test = OverTen(2);

if ( NefariousProgrammersBirthday() )
{
test = true;
}

if ( test )
{
PayoutCash();
}
else
{
ResetMachine();
}

I'm sure you can see where this is going.

but, but but, you're going to argue that I'm assigning to auto, I'm not using "const auto".  Well that's my point, I want the warning to tell the programmer that they're assigning my const return type to a non-const auto, that they should be using "const auto" and hence close this loop hole.

Instead the compiler warns you that your API, the return being const, has no effect.  It should have an effect, the return is constant and it should be hard to get rid of that constness.

For instance if one had to const_cast like so:

auto test = OverTen(2);
if ( NefariousProgrammersBirthday() )
{
test = const_cast<bool>(test);
test = true;
}

Well, that jumps out at you, as would

auto test = const_cast<bool>(OverTen(2));

or even

auto test = (bool)OverTen(2);

So, I would suggest that if a return type has const the auto becomes "const auto" immediately, attempts to change this are easy to spot.

And -Wignored-qualifiers should NOT report a warning on a const qualification of a return, because it is being used in the auto case, and then if it were being assigned to a mutable type:

bool test = OverTen(2);

Then you should truly get an ignored-qualifiers warning, because the const on the function result is being ignored.

No comments:

Post a Comment