问题
Is there a syntax, template or function that allows me to essentially turn any value into a pointer to that value? I.e. copy it to the gc heap and return a pointer to it? "new" doesn't work for all types, std.experimental.allocator doesn't work in ctfe, and both seem to have troubles making pointers to delegates.
回答1:
You can put the data in question inside a struct
, then use the new
keyword on that struct.
T* copy_to_heap(T)(T value) {
// create the struct with a value inside
struct S {
T value;
}
// new it and copy the value over to the new heap memory
S* s = new S;
s.value = value;
// return the pointer to the value
return &(s.value);
}
void main() {
// example use with a delegate:
auto dg = copy_to_heap(() { import std.stdio; writeln("test"); });
(*dg)();
}
That assumes you already have a value to copy but that's probably easier and the way you'd do it anyway. But you can also tweak the code to remove that requirement if you want (perhaps just pass typeof.init for example).
来源:https://stackoverflow.com/questions/58736420/syntax-to-heap-allocate-anything