digitalmars.D - array setting with objects (bug?)
- Denton Cockburn (29/29) Mar 04 2008 Is this a bug?
 - Denton Cockburn (1/1) Mar 04 2008 D 1.027 by the way.
 - Jarrett Billingsley (6/10) Mar 04 2008 This creates *one* instance of C and sets all the elements of arr to poi...
 - Denton Cockburn (10/25) Mar 04 2008 Yeah, would be nice if that was mentioned somewhere.
 - bearophile (4/6) Mar 04 2008 I think the current behavior is better, despite being a little less intu...
 
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
"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
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...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?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
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








 
 
 
 Denton Cockburn <diboss hotmail.com> 