Pure, Nothrow in Generic Programming

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Fri Nov 27 14:55:28 PST 2009


Don wrote:
> Andrei Alexandrescu wrote:
>> Walter Bright wrote:
>>> dsimcha wrote:
>>>> I think you misunderstood the argument.  memcmp() could be @trusted 
>>>> if functions
>>>> only need to be safe when passed valid parameters, though I don't 
>>>> necessarily
>>>> agree that this makes sense.  I was thinking memcmp() shouldn't even 
>>>> be marked
>>>> @trusted because it's so easy to invoke undefined behavior by 
>>>> passing incorrect
>>>> parameters.  This would mean that, if opCmp() uses it, opCmp() 
>>>> couldn't be marked
>>>> as @safe.
>>>
>>> memcmp() could be marked @trusted, but it should not be. This is 
>>> because @trusted functions can be called by @safe ones, but there's 
>>> no way that an @safe function can guarantee it sends memcmp() 
>>> arguments that will work safely with memcmp().
>>>
>>> Whoever calls memcmp() can be marked @trusted.
>>
>> Hm, if we think of it, memcmp can be @safe no problem. This is beacuse 
>> it oly reads stuff. There are three possible outcomes:
>>
>> a) valid addresses, all's fine
>>
>> b) incorrect addresses within the application, erroneous result returned
>>
>> c) incorrect addresses outside the application, segfault
>>
>> None of the above is unsafe. So memcmp is safe. (In contrast, memcpy 
>> is not). Color me surprised but convinced.
>>
>>
>> Andrei
> 
> Although Walter had previously talked about making @safe a little 
> stronger than just memory safety -- with the goal of eliminating 
> undefined behaviour. So (b) would be a problem.

I think it would be implementation-defined behavior - in case (b) memcmp 
would return an implementation-defined value but still defined.

> After all, you could you 
> use the same argument to say that array bounds checking isn't required 
> for reads, only for writes.

Well less so. Reading an array element off-bounds that's of an elaborate 
type with indirections will lead to UB.


Andrei



More information about the Digitalmars-d mailing list