Passing dynamic arrays
Steven Schveighoffer
schveiguy at yahoo.com
Mon Nov 8 11:44:36 PST 2010
On Mon, 08 Nov 2010 14:22:36 -0500, Ali Çehreli <acehreli at yahoo.com> wrote:
> Steven Schveighoffer wrote:
> > On Mon, 08 Nov 2010 13:35:38 -0500, Daniel Gibson
> >> If you pass a dynamic array to a function and chance it's size within
> >> the function, you have undefined behaviour - you never know if it
> will
> >> affect the original array (from the calling function) or not.
> >
> > Not exactly. If you happen to change its size *and* change the
> original
> > data afterwards, then it's somewhat undefined
>
> Let's also note that appending to the array qualifies as "change its
> size *and* change the original data afterwards." We cannot be sure
> whether appending affects the passed-in array.
No, it doesn't. If you are appending to data that was passed in, you are
not changing the *original data* passed in. You are only appending to it.
for example:
char[] s = "foo".dup;
s ~= "bar";
does not change the first 3 characters at all. So any aliases to s would
not be affected. However, any data aliased to the original s may or may
not be aliased to the new s. Once you start changing that original data
(either via s or via an alias to the original s), this is where the
confusing behavior occurs.
In my experience, this does not cause a problem in the vast majority of
cases.
-Steve
More information about the Digitalmars-d
mailing list