any news on const/invariant?

Leandro Lucarella llucax at gmail.com
Tue Nov 27 06:57:09 PST 2007


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


-- 
Leandro Lucarella (luca) | Blog colectivo: http://www.mazziblog.com.ar/blog/
----------------------------------------------------------------------------
GPG Key: 5F5A8D05 (F8CD F9A7 BF00 5431 4145  104C 949E BFB6 5F5A 8D05)
----------------------------------------------------------------------------
Hey you, would you help me to carry the stone?
Open your heart, I'm coming home.



More information about the Digitalmars-d mailing list