Syntax to heap allocate anything?

て烟熏妆下的殇ゞ 提交于 2019-12-11 06:55:01

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!