1

我对 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
}
4

1 回答 1

1

要直接回答问题 - 使用align(N)指定您想要的对齐方式。但是,请记住这一点(引自 dlang.org):Do not align references or pointers that were allocated using NewExpression on boundaries that are not a multiple of size_t

http://dlang.org上的参考手册有一个关于对齐的部分 - http://dlang.org/attribute.html#align

比如说,T 是 int - edge!int 在 64 位架构上已经是 24 字节大。D在对齐上与C没有太大区别。检查以下(可运行/可编辑代码:http ://dpaste.dzfl.pl/de0121e1 ):

module so_0001;
// http://stackoverflow.com/questions/11383240/custom-alignment-options-for-an-efficient-quad-edge-implementation

struct edge(T) {
    edge* next;
    T* data;
    uint position;
}
alias edge!int iedge;
alias edge!int[4] qedge;

/* not a good idea for struct... it is a value type...
edge!int new_edge() {
    // in the original example it used new... D is not C++ to mix value and reference types! :)
}
*/

import std.stdio;

int main() {
    writeln(iedge.sizeof);

    //                                   64bit
    //                                ----------
    writeln(iedge.next.offsetof);     // 0
    writeln(iedge.data.offsetof);     // 8
    writeln(iedge.position.offsetof); // 16
    writeln(qedge.sizeof);
    return 0;
}
于 2012-07-08T13:48:41.017 回答