RAII and classes

John Colvin via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Mar 9 02:28:06 PST 2016


Potential for leaking references from alias this aside, is there 
some reason that I shouldn't do this for all my C++-like RAII 
needs:

class A
{
	~this(){ import std.stdio; writeln("hello"); }
}

auto RAII(T)()
if (is(T == class))
{
	struct Inner
	{
		private ubyte[__traits(classInstanceSize, T)] buff;
		T c;
		alias c this;
		
		~this()
		{
			destroy(c);
		}
	}
	Inner tmp;
	import std.conv : emplace;
	tmp.c = tmp.buff.emplace!T;
	return tmp;
}

void main()
{
	auto a = RAII!A;
}


More information about the Digitalmars-d-learn mailing list