Created
December 2, 2020 17:15
-
-
Save PetarKirov/f7b6c3b7e4f8fe10c0a2dbf0d3f44471 to your computer and use it in GitHub Desktop.
D statically allocated class instnace
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
void main() | |
{ | |
throw globalInstance!Error("This is an Error()", null); | |
} | |
T globalInstance(T, bool tls = true, Args...)(auto ref Args args) | |
if (is(T == class)) | |
{ | |
// There really should be a trait for this: | |
enum classAlignment = 2 * (void*).sizeof; // until then, here's a reasonable guess :) | |
enum objSize = __traits(classInstanceSize, T); | |
static if (tls) | |
static align(classAlignment) void[objSize] _store; | |
else | |
static __gshared align(classAlignment) void[objSize] _store; | |
static T get() | |
{ | |
_store[0 .. __traits(classInstanceSize, T)] = typeid(T).initializer[]; | |
return cast(T) _store.ptr; | |
} | |
auto typedStore = (cast(T function() @trusted pure nothrow @nogc) &get)(); | |
import core.lifetime : emplace; | |
return emplace!T(typedStore, args); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment