## digitalmars.D - Should slice[]=slice be disallowed?

=?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
(This must have been discussed before, but I couldn't come up with a way
to search in the archives.)

There is a hidden danger with two uses of slices:

double[] slice1 = [ 1, 1, 1];
double[] slice2 = [ 2, 2, 2];
double[] slice3 = [ 3, 3, 3];

slice2 = slice1;              // (1)
slice3[] = slice1;            // (2)

The last two lines mean very different things:

(1) start sharing elements with slice1

(2) copy slice1's elements

If either gets used by accident, the difference may not be noticed until
the elements are modified in the future.

Could we limit the syntax to reduce the chances of such a risk? e.g.
"When two slices are involved, both sides must use the array-wise
syntax". Then the second line had to be written as:

slice3[] = slice1[];

Ali
Feb 02 2011
=?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
Ali Çehreli wrote:
(This must have been discussed before, but I couldn't come up with a way
to search in the archives.)

There is a hidden danger with two uses of slices:

double[] slice1 = [ 1, 1, 1];
double[] slice2 = [ 2, 2, 2];
double[] slice3 = [ 3, 3, 3];

slice2 = slice1;              // (1)
slice3[] = slice1;            // (2)

The last two lines mean very different things:

(1) start sharing elements with slice1

(2) copy slice1's elements

If either gets used by accident, the difference may not be noticed until
the elements are modified in the future.

Could we limit the syntax to reduce the chances of such a risk? e.g.
"When two slices are involved, both sides must use the array-wise
syntax".
Oy! :( I meant the above only in the array-wise semantics. Both of these should be valid with their different meanings: slice2 = slice1; slice3[] = slice1[]; This is still ok: slice2 = slice1[]; // a slice to "all of" slice1 This should be illegal: slice3[] = slice1; Should it be? Ali
Feb 02 2011
bearophile <bearophileHUGS lycos.com> writes:
Ali Çehreli:

(This must have been discussed before, but I couldn't come up with a way
to search in the archives.)