any news on const/invariant?

Christopher Wright dhasenan at gmail.com
Tue Nov 27 08:35:25 PST 2007


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.

Though in the calling method, the buffer length wouldn't change, so if 
there isn't a realloc, the change is still lost.

> 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).
> 
> 



More information about the Digitalmars-d mailing list