Skip to content

Instantly share code, notes, and snippets.

@Dav1dde
Forked from JakobOvrum/gist:3196553
Created July 29, 2012 08:12
Show Gist options
  • Save Dav1dde/3196600 to your computer and use it in GitHub Desktop.
Save Dav1dde/3196600 to your computer and use it in GitHub Desktop.
initOnce function
import std.stdio;
bool initOnce(alias var)(lazy typeof(var) init)
{
static bool hasInitialised = false;
if(!hasInitialised)
{
var = init();
hasInitialised = true;
}
return hasInitialised;
}
void test()
{
static Object o;
writeln(cast(void*)o);
initOnce!o(new Object);
}
void test2()
{
static Object o;
writeln(cast(void*)o);
initOnce!o(new Object);
}
void main()
{
foreach(i; 0 .. 3)
test(); // printed null, 472FD0 and 472FD0
test2();
test2();
}
/* Output:
─[ArchBox][/tmp]╼ ./s
null
B73B1FF0
B73B1FF0
null
B73B1FE0
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment