[cfe-dev] Default arguments considered harmful?

David Blaikie dblaikie at gmail.com
Fri May 2 10:42:37 PDT 2014


On Fri, May 2, 2014 at 9:40 AM, Philip Reames <listmail at philipreames.com> wrote:
>
> On 05/02/2014 02:18 AM, David Chisnall wrote:
>>
>> On 2 May 2014, at 09:16, David Tweed <david.tweed at arm.com> wrote:
>>
>>> I wonder if, with C++11 named initialization syntax for PODs, something
>>> could be done so that in cases like this a (function specific, I guess)
>>> "optional options object" could be used. (This would avoid one of the big
>>> problems with C++ optional arguments, which is that if one towards the
>>> end
>>> needs to be set to a non-default value all the preceding options need
>>> setting.) That would certainly make things a lot easier to read in cases
>>> like these.
>>
>> The related issue is that they complicate overloading.  I've been bitten a
>> few times in clang code by the compiler deciding that, when I specified a
>> pointer instead of a reference for a parameter, it would happily coerce it
>> to a bool and then use the default values for the rest of the parameters,
>> giving some very strange results - no errors, no warnings, just the code
>> doing something unexpected.
>>
>> David
>>
> David, I think you're pointing out a slightly different issue... one I've
> also been bitten by.
>
> Does anyone know of a legitimate reason to have an implicit conversion to
> bool as a function argument?  Maybe we should add an optional warning for
> this case in particular?

My suspicion is that this would (just barely) not meet our bar for
false positive rate. (my bet, though it's not a sure thing, is that we
do this in the LLVM project at least tens of times intentionally (ie:
not a bug, but subtle code))

But, arguably, rewriting the argument from "func(x)" to "func(x !=
nullptr)" is a benefit in readability and sometimes we're OK with a
few more false positives if they're just "badly written/confusing
code"

- David



More information about the cfe-commits mailing list