我对 D2 编程语言相当陌生。我需要实现一个四边形数据结构。这是一种用于有效图嵌入及其对偶的邻接数据结构。根据之前的 C 经验,我从以下实现开始:
struct edge(T) {
edge* next;
T* data;
uint position;
}
alias edge[4] qedge;
edge* new_edge() {
qedge* q = new qedge; // does not compile, just analogous
// initialize the four edges (q[i].position = i)
return cast (edge*) q;
}
这很好用,但是这个位置字段让我很烦——它只是在浪费空间。有没有办法在为 qedge 数组分配内存时对齐 (8 * ${machine word size}) 边界(然后我不需要额外的位置字段,因为边缘在 qedge 中的哪个位置的信息数组将被编码到边缘地址)?
我的目标是一个高效而可爱的实现(这就是我选择 D 的原因),所以欢迎任何其他建议。
编辑:这是一段让事情更清楚的代码http://dpaste.dzfl.pl/e26baaad:
module qedge;
class edge(T) {
edge next;
T* data;
}
alias edge!int iedge;
alias iedge[4] qedge;
import std.stdio;
import std.c.stdlib;
void main() {
writeln(iedge.sizeof); // 8
writeln(qedge.sizeof); // 32
// need something for the next line,
// which always returns an address, divisible by 32
qedge* q = cast (qedge*) malloc(qedge.sizeof);
writeln(q); // ex. 0x10429A0 = 17050016, which is, does not start at 32-byte boundary
}