any news on const/invariant?
Steven Schveighoffer
schveiguy at yahoo.com
Tue Nov 27 09:42:19 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.
>
> 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"
-Steve
More information about the Digitalmars-d
mailing list