"template with auto ref" experiment

Alex via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Feb 4 06:33:12 PST 2017


Having read this
https://dlang.org/spec/template.html#auto-ref-parameters

I tried to do something like this

// Code starts here
void main()
{
	initStruct iSb;
	iSb.var = 3;
	A b = A(iSb);
	assert(*b.myVar == 3); // this works
	iSb.var = 4;
	assert(*b.myVar == 4); // as expected
	
	b = A(initStruct(5)); // how does
	assert(*b.myVar == 5); // this work?
}

struct A
{
	@disable this();
	size_t* myVar;
	this()(auto ref initStruct iS) @nogc
	{
		import core.stdc.stdio;
		__traits(isRef, iS) ? printf("ref case\n") : printf("value 
case");
		
		myVar = &iS.var;
		
		/* // This treatment is not needed?
		if(__traits(isRef, iS))
		{
			myVar = &iS.var;
		}
		else
		{
			myVar = new size_t(iS.var);
		}
		*/	
	}
}

struct initStruct
{
	size_t var;
}
// Code ends here

All asserts pass. But the question is how it is possible to avoid 
the allocation of memory for the member var of the struct A in 
the second case. Is the input remains somewhere and I'm not aware 
of this?
By the way, I find the fact very cool. I'm just wondering, 
whether I'm doing something unsecure...


More information about the Digitalmars-d-learn mailing list