Passing dynamic arrays

Jens Mueller jens.k.mueller at gmx.de
Tue Nov 9 03:34:53 PST 2010


> > > I don't really have any good use-case examples. Maybe an initialization
> > > function? Developed your own number object (big int) and were thinking
> > > in terms of it being a refrence you thought
> > > 
> > > a = a + BigInt(7);
> > > 
> > > would result in a being resigned in the calling function. Or maybe just a
> > > function that swaps two class references:
> > > 
> > > void swap(T)(T a, T b) { // Correct void swap(T)(ref T a, ref T b) {
> > > 
> > >     auto tmp = a; a = b; b = tmp;
> > > 
> > > }
> > > 
> > > Actually that turned out to be a pretty good one.
> > 
> > I do see why a = new A() is useful. But it makes only sense if I passed
> > a/b as ref a/b. Basically I wonder why I do not get a warning when
> > changing the reference in that situation. So my question is more why am
> > I allowed to change the reference even though I didn't pass it as ref a.
> > I was looking for a use of that. Assuming there is good use then there
> > is no reason to forbid it. But if there is no good use I'd like to be
> > warned when compiling the above swap. Because it's an error.
> > For dynamic arrays slicing is a good example to allow it. But why should
> > it be allowed for objects?
> 
> Why wouldn't you be able to change it? You can change any parameter as long as 
> it's not const or immutable (or in, which implies const). The fact that it's a 
> referenc is irrelevant. I can assign whatever I want to references and pointers 
> in a function whether they were passed in or not. Sure, if you want to alter the 
> original pointer or reference, that's not going to work unless it was passed as 
> ref, but that's the same as any other parameter. Why would you expect altering  
> a reference to alter the original? Sure, altering what it _refers to_ should 
> alter what the original refers to because they refer to the same thing, but 
> altering the reference itself shouldn't alter the original because they're two 
> different references.
> 
> There is no reason why parameters should have to stay the same as what they were 
> passed in as - regardless of whether they're value types or reference types. If 
> you want that behavior, use const, in, or immutable.

I see your point. You argue that the behavior is consistent. My point is
that this consistency can lead to bugs. I may forget the ref. But I'll
keep in mind to never forget the ref if it is needed.

Jens


More information about the Digitalmars-d mailing list