Reset all Members of a Aggregate Instance

Tofu Ninja via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Dec 3 20:21:34 PST 2015


On Friday, 4 December 2015 at 04:08:33 UTC, Tofu Ninja wrote:
> On Thursday, 3 December 2015 at 21:04:00 UTC, Nordlöw wrote:
>> ...
>
> I think reflection will be a bad choice for this because of 
> private members and what not.
> I think the correct way is:
>
> void reset(C)(ref C c)
> {
> 	static if(is(C == class))
> 	{
> 		auto init = typeid(c).init();
> 		auto objmem = ((cast(void*)c)[0 .. init.length]);
> 		if(init.ptr == null) (cast(byte[])objmem)[] = 0;
> 		else objmem[] = init[];
> 		if(c.classinfo.defaultConstructor != null)
> 			c.classinfo.defaultConstructor(c);
> 	}
> 	else c = C.init;
> }
>
> Seems to work for structs, classes, and basic types. It even 
> calls the default constructor for classes, even if there is 
> inheritance and the object passed in is not actually C but a 
> sub class of C.

Oh after reading chris's post, probably should change to...

void reset(C)(ref C c)
{
	static if(is(C == class))
	{
		auto type_info = typeid(c);
		auto class_info = c.classinfo;
		destroy(c);
		auto init = type_info.init();
		auto objmem = ((cast(void*)c)[0 .. init.length]);
		if(init.ptr == null) (cast(byte[])objmem)[] = 0;
		else objmem[] = init[];
		if(class_info.defaultConstructor != null)
			class_info.defaultConstructor(c);
		else throw new Exception("No default constructor");
	}
	else c = C.init;
}


More information about the Digitalmars-d-learn mailing list