D array expansion and non-deterministic re-allocation

Bartosz Milewski bartosz-nospam at relisoft.com
Tue Nov 24 23:49:14 PST 2009


Steven Schveighoffer Wrote:


> Bottom line: if a function isn't supposed to change the buffer, the  
> signature should be const for that parameter.  It's one of the principles  
> of const, and why it's in D2 in the first place.  I'd explain to the coder  
> that he is wrong to expect that modifying a buffer in a function that  
> isn't supposed to modify a buffer is acceptable (and hopefully he gets it,  
> or else I don't have time to deal with people who insist on being right  
> when they are not).
> 
> BTW, in my experience, the newbie expectaction of ~= is usually that it  
> modifies the original even when it doesn't, not the other way around.
> 

The guy insists that the reallocation happens in the quote function (otherwise there would be stomping), so no sharing happens and the original is not modified. He tested it on a variety of inputs! I'm not totally making it up--I had this kind of arguments with C++ programmers. You tell them that it's safer to use const and they laugh at you. "My code works, why should I change it!"

> >> Second, the optimizer cannot do simple math optimization on src.length -=  
> 1 and src.length += 1 because length is a property, not a field.  Setting  
> the length calls a function, which cannot be optimized out.
 
You are again resorting to implementation. I guess in the current implementation it's true that the compiler will indeed insert a call to its internal function. But the language spec does not proscribe that. 

Would you also argue that this optimization is incorrect? Changing:

a.length += 2;
a.length += 3;

to:

a.lenght += 5;

I'm not saying that this is an unsolvable problem. I'm just showing how hard it is to reason about D arrays. 




More information about the Digitalmars-d mailing list