www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - RAII and classes

reply John Colvin <john.loughran.colvin gmail.com> writes:
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;
}
Mar 09 2016
parent reply cym13 <cpicard openmailbox.org> writes:
On Wednesday, 9 March 2016 at 10:28:06 UTC, John Colvin wrote:
 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;
 }
That's almost literally what std.typecons.scoped does.
Mar 09 2016
parent John Colvin <john.loughran.colvin gmail.com> writes:
On Wednesday, 9 March 2016 at 10:48:30 UTC, cym13 wrote:
 On Wednesday, 9 March 2016 at 10:28:06 UTC, John Colvin wrote:
 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;
 }
That's almost literally what std.typecons.scoped does.
Ok, I forgot std.typecons.scoped, nothing to see here .....
Mar 09 2016