www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - array setting with objects (bug?)

reply Denton Cockburn <diboss hotmail.com> writes:
Is this a bug?

import std.stdio;

class C
{
	int[] x;
}

void main()
{
	C[] arr;
	arr.length = 3;
	arr[] = new C; /* this is the offending line, it doesn't happen if I */
			/*initalize each independently */
	
	foreach (ref c; arr)
	{
		c.x ~= 5;
		writefln(c.x);
	}
}

the printed result is:
[5]
[5,5]
[5,5,5]

I expected it to be:
[5]
[5]
[5]

I didn't find any explanation for this kind of behaviour in the docs, and
it does seem like a bug to me.
Mar 04 2008
next sibling parent Denton Cockburn <diboss hotmail.com> writes:
D 1.027 by the way.
Mar 04 2008
prev sibling parent reply "Jarrett Billingsley" <kb3ctd2 yahoo.com> writes:
"Denton Cockburn" <diboss hotmail.com> wrote in message 
news:pan.2008.03.04.13.32.00.785638 hotmail.com...

 arr[] = new C; /* this is the offending line, it doesn't happen if I */

This creates *one* instance of C and sets all the elements of arr to point to that single instance. Hence:
 [5]
 [5,5]
 [5,5,5]

You keep modifying the same array. :)
Mar 04 2008
parent reply Denton Cockburn <diboss hotmail.com> writes:
On Tue, 04 Mar 2008 08:53:35 -0500, Jarrett Billingsley wrote:

 "Denton Cockburn" <diboss hotmail.com> wrote in message 
 news:pan.2008.03.04.13.32.00.785638 hotmail.com...
 
 arr[] = new C; /* this is the offending line, it doesn't happen if I */

This creates *one* instance of C and sets all the elements of arr to point to that single instance. Hence:
 [5]
 [5,5]
 [5,5,5]

You keep modifying the same array. :)

Yeah, would be nice if that was mentioned somewhere. in the section of the docs where: s[] = 3; // same as s[0] = 3, s[1] = 3, s[2] = 3 I (naively) expected: s[] = new C; // to be same as s[0] = new C, s[1] = new C, s[2] = new C or s[] = foo(); // where foo returns an object (a different one each time) easy to work with and around as is, but would be rather nice to be able to do what I just stated. Syntactic sugar for 2.0?
Mar 04 2008
parent bearophile <bearophileHUGS lycos.com> writes:
Denton Cockburn:
 easy to work with and around as is, but would be rather nice to be able to
 do what I just stated.  Syntactic sugar for 2.0?

I think the current behavior is better, despite being a little less intuitive, because it's more uniform: it copies the value to all the cells. In such situation the value is the object reference, that is many references to the same object. So I think that sugar you talk about is bad for your health in the long run. Bye, bearophile
Mar 04 2008