如何在不进行 GC 分配的情况下初始化 D 中的静态数组?
在 D 中,所有数组文字都是动态数组,因此由 GC 分配。
即使在这个简单的示例中:
int[3] a = [10, 20, 30];
数组也是在堆上分配的,然后复制到 a
中。
您应该如何在没有堆分配的情况下初始化静态数组?
您可以手动完成:
int[3] a = void;
a[0] = 10;
a[1] = 20;
a[2] = 30;
但这充其量是乏味的。
有更好的办法吗?
In D, all array literals are dynamic arrays, and are therefore allocated by the GC.
Even in this simple example:
int[3] a = [10, 20, 30];
The array is heap-allocated and then copied into a
.
How are you supposed to initialise a static array without heap-allocation?
You could do it manually:
int[3] a = void;
a[0] = 10;
a[1] = 20;
a[2] = 30;
But this is tedious at best.
Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这将在数据段中放置一个常量副本。您可以通过简单的赋值 (
auto copy = a;
) 在堆栈上创建一个副本(不涉及堆分配)。This will place a constant copy in the data segment. You can create a copy on the stack (that doesn't involve a heap allocation) with a simple assignment (
auto copy = a;
).我认为如果您可以将文字全局声明为不可变的,然后使用它作为初始化器,则没有堆分配 - 但我可能是错的,我不确定。
I think if you could declare the literal as
immutable
globally, then use that as the initializer, there's no heap allocation -- but I may be wrong, I'm not sure.我认为您可能有点错误:在 http://www .digitalmars.com/d/2.0/arrays.html#static-init-static
代码示例
意味着
const a[3] = [10, 20, 30];
不会/不应该在堆上分配任何内容I think you might be a bit mistaken: in http://www.digitalmars.com/d/2.0/arrays.html#static-init-static
with code example
that means that
const a[3] = [10, 20, 30];
won't/shouldn't allocate anything on the heap这只是一个编译器错误。我在 DMD 的 bugzilla 中看到了它。现在应该已修复(DMD 2.055)。
It's just a compiler bug. I saw it in DMD's bugzilla. It should be fixed by now (DMD 2.055).
2017 更新:在 DMD 的任何最新版本中,在静态数组上使用数组初始值设定项不再分配,即使静态数组是局部变量(即堆栈分配)。
您可以通过创建一个初始化静态数组的函数来亲自验证这一点,然后将该函数标记为 @nogc 并观察它是否可以编译。示例:
由于 testfunc() 尽管是 @nogc 仍然可以编译,所以我们知道数组初始值设定项不会分配。
2017 UPDATE: In any recent version of DMD, using an array initializer on a static array no longer allocates, even if the static array is a local variable (ie stack-allocated).
You can verify this yourself by creating a function where a static array is initialized, and then marking the function as @nogc and observing whether or not it compiles. Example:
Since testfunc() compiles despite being @nogc, we know that the array initializer does not allocate.