any news on const/invariant?

Regan Heath regan at netmail.co.nz
Tue Nov 27 09:45:43 PST 2007


Steven Schveighoffer wrote:
> "Leandro Lucarella" wrote
>> Frank Benoit, el 27 de noviembre a las 11:01 me escribiste:
>>> Regan Heath schrieb:
>>>> Walter Bright wrote:
>>>>> Regan Heath wrote:
>>>>>> void foo(char[] pbuffer)
>>>>>> {
>>>>>>   //assume this causes reallocation
>>>>>>   //assume there is no more space in place
>>>>>>   pbuffer ~= "a";
>>>>>> }
>>>>>>
>>>>>> void main()
>>>>>> {
>>>>>>   char[] buffer = "test".dup;
>>>>>>   foo(buffer);
>>>>>>   buffer[0] = 'a' //crash
>>>>>> }
>>>>>>
>>>>>> Right?
>>>>> No. foo() modifies its copy of pbuffer, which is not the same as 
>>>>> buffer.
>>>> Yes, but the underlying memory is reallocated so buffer no longer 
>>>> points
>>>> to valid memory, right?
>>>>
>>>> Regan
>>> You missed a semicolon, so it does not compile :)
>>> Realloc does not destroy the original buffer. So your foo just make a
>>> modified copy, that is not visible for the caller. buffer will stay
>>> unchanged.
>> I think you are missing an important point here: string concatenation is a
>> fairly common case where is really obscure to figure out if the undelying
>> pointer gets changed or not. When a user writes pbuffer ~= "a"; it's not
>> very intuitive to expect a realocation and pbuffer.ptr change.
>>
>> This could lead to some hard to find bugs, because of the lack of
>> explicitness and non-determinism (so to speak) where pbuffer ~= "a"; could
>> lead or not to reallocation (or the fact that pbuffer[0] = 'a' will
>> survive the local function and concatenation *may* survive or may not).
> 
> It is very deterministic actually.  From 
> http://www.digitalmars.com/d/arrays.html
> 
> "Concatenation always creates a copy of its operands, even if one of the 
> operands is a 0 length array"

True, but the example after that statement is:

a = b ~ c[0..0];

whereas foo is doing:

a ~= b;

which does not necessarily have to make a copy, it could reallocate 'a'.

An in fact it does.  It either reallocates if it can do so in place or 
creates a new copy.  That plus the fact that the callers array length 
never changes means you're right, it's deterministic.

Regan



More information about the Digitalmars-d mailing list