是否有语法、模板或函数允许我将任何值转换为指向该值的指针?例如,将其复制到gc堆并返回指向它的指针?"new“并不适用于所有类型,std.experimental.allocator在ctfe中也不起作用,而且两者在指向委托的指针上似乎都有问题。
发布于 2019-11-07 03:03:41
您可以将有问题的数据放在struct中,然后在该结构上使用new关键字。
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)();
}这假设你已经有了一个要复制的值,但这可能更容易,而且你无论如何都会这样做。但是,如果您愿意,也可以调整代码以删除该要求(例如,可能只需传递typeof.init )。
https://stackoverflow.com/questions/58736420
复制相似问题