堆的语法分配什么? [英] Syntax to heap allocate anything?

查看:73
本文介绍了堆的语法分配什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有语法,模板或函数可以让我将任何值转换为指向该值的指针?即将其复制到gc堆并返回指向它的指针? new不适用于所有类型,std.experimental.allocator不适用于ctfe,而且似乎都难以建立指向代理的指针。

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.

推荐答案

您可以将有问题的数据放入结构中,然后使用 new

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)();
}

这假设您已经具有复制价值,但是这可能会更容易无论如何你都会这样做。但是您也可以根据需要调整代码以删除该要求(例如,只需传递typeof.init即可)。

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).

这篇关于堆的语法分配什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆