On 26 September 2011 09:32, Jon Grant wrote:
> Hello
>
> Jonathan Wakely wrote, On 26/09/11 08:10:
>>
>> On 26 September 2011 05:29, Ian Lance Taylor wrote:
>>>
>>> Jon Grant<j...@jguk.org>  writes:
>>>
>>>> Currently gcc, and g++ don't give a warning when a pointer was
>>>> converted to a bool, in the same way it is for other types.
>>
>> At least in C++, it's not really true to say "in the same way it is
>> for other types" because you cannot convert from a pointer to any
>> integer type except bool.  Your test uses NULL for the other integer
>> types, which is an integral constant expression with value zero, so
>> it's ok to convert that to an integer type. That's not true for
>> general pointer values: if your test used m_int(g_glob) then it
>> wouldn't compile.
>
> Good point. My test should have used g_glob due to NULL being a macro of 0
> in C++.

That wouldn't compile. A pointer to boolean conversion is safe and well-defined.

>>> There is a lot of code which uses
>>>    if (p)
>>> where p is a pointer to test whether p is not NULL.  I don't think we
>>> could reasonably have gcc warn about such a case.
>>>
>>> We might be able to separate out conversion to bool on assignment from
>>> conversion to bool in a test, though.
>>
>> That would still break this:
>>
>> Base* p = getObj();
>> bool is_derived = dynamic_cast<Derived*>(p);
>>
>> What problem is the warning supposed to solve?
>
> A programmer assigning a bool with a pointer, there's an implicit evaluation
> there isn't there? rather than:
>
> bool invalid = (NULL == p);

Why is that preferable?


> I expect this depends on what the standard allows then.


4.12 Boolean conversions [conv.bool]
1  A prvalue of arithmetic, unscoped enumeration, pointer, or pointer
to member type can be converted to a
prvalue of type bool. A zero value, null pointer value, or null member
pointer value is converted to false;
any other value is converted to true. A prvalue of type std::nullptr_t
can be converted to a prvalue of
type bool; the resulting value is false.

Reply via email to