WTF did happen with struct constructor and ref in 2.061 ?

Maxim Fomin maxim at maxim-fomin.ru
Fri Jan 4 07:03:23 PST 2013


On Friday, 4 January 2013 at 12:12:53 UTC, js.mdnq wrote:
>
> There is no semantic difference between
>
> S s = S(2); foo(s)
>
> and
>
> foo(S(2));
>

In the first case dtor (if any) is called at the end of the 
scope, in the second after expression being evaluated. It also 
may influence optimization.

Consider this:

import std.stdio;

struct S { ~this() { writeln("dtor"); } }

void foo(ref S s)
{
	writeln("ref");
}

void foo(S s)
{
	writeln("non-ref");
}

void one()
{
	S s;
	foo(s);
	writeln("end");
}

void two()
{
	foo(S());
	writeln("end");
}

void main()
{
	one();
	two();
}

Output is:

ref
end
dtor
ref
dtor
end

If dmd supports struct lvalues by creating a temporary, then this 
temporary would be passed by reference, be modified and 
immidiately thrown away (although it depends on what dmd actually 
did - I have the latest version now and cannot check old 
behavior). This can lead to bugs caused by changing structs and 
not saving their state.


More information about the Digitalmars-d mailing list