是否有语法、模板或函数允许我将任何值本质上转换为指向该值的指针? IE。将其复制到GC堆并返回指向它的指针? “new”并不适用于所有类型,std.experimental.allocator 不适用于 ctfe,并且两者似乎都在指向委托时遇到了麻烦。
您可以将有问题的数据放入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 )。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)