Pure, Nothrow in Generic Programming

Don nospam at nospam.com
Fri Nov 27 08:03:06 PST 2009


dsimcha wrote:
> == Quote from Walter Bright (newshound1 at digitalmars.com)'s article
>> dsimcha wrote:
>>> I would say that @safe doesn't make much sense.  What if you're implementing your
>>> comparison function using memcmp() or something else that involves a bunch of
>>> pointers?  If you pass memcmp() invalid parameters, it can segfault, and would
>>> therefore have to be marked as unsafe, meaning that safe functions couldn't
> call it.
>> A safe function is only safe if the parameters passed to it are valid.
>> memcmp() cannot be safe as it does pointer arithmetic.
> 
> 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.

It seems to me that one of the most important features of SafeD is that 
whenever a @safe function invokes a function, it does so only with valid 
parameters. The problem with memcmp() is that the required relationship 
between the parameters is complicated, and can't be determined 
statically by the compiler.
The fact that internally it does pointer arithmetic is a symptom of this 
problem: it might be accessing memory which is not implied by the 
parameters. So memcmp() cannot be @trusted.
Likewise, if it contains asm, it might be accessing non-parameter memory.

OTOH, this contains pointer arithmetic but is perfectly fine:

bool ptrcmp(char *x, char *y)
{
     char *z = x+100;
     return y < z;
}



More information about the Digitalmars-d mailing list