-
-
Save Dav1dde/3196600 to your computer and use it in GitHub Desktop.
initOnce function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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