DMD 0.177 release

Tom S h3r3tic at remove.mat.uni.torun.pl
Sat Dec 9 18:54:48 PST 2006


Walter Bright wrote:
> Jarrett Billingsley wrote:
>> What is the TRUE reason you don't want to give structs ctors?  I don't 
>> want to know why static opCalls are good, but why ctors are bad. 
> 
> Constructor:
> 
>     S(v);
> 
> static opCall:
> 
>     S(v)
> 
> What's the difference? I just don't see the point for adding constructors.

The difference is that a ctor initializes an already-existing instance, 
while static opCall returns one, which is then copied. A static opCall 
won't handle the following case:

----

void delegate() globalDG;


struct Foo {
	void func() {
		printf("myVal = %d\n", myVal);
	}

	static Foo opCall(int v) {
		Foo res;
		res.myVal = v;
		globalDG = &res.func;
		return res;
	}

	int myVal;
}


void main() {
	Foo f = Foo(5);
	globalDG();  // prints garbage instead of '5'
}

----

The Foo instance returned from static opCall is copied, thus the 'ctor 
hack' doesn't have real access to the object it's constructing, not to 
mention the overhead of copying the struct to another place on stack...

Also,  new Foo(5)  isn't going to work without real ctors or more hacks.



--
Tomasz Stachowiak



More information about the Digitalmars-d-announce mailing list