代码之家  ›  专栏  ›  技术社区  ›  Å imon Tóth

发行新股

c++
  •  8
  • Å imon Tóth  · 技术社区  · 14 年前

    在这 I need C++ array class template, which is fixed-size, stack-based and doesn't require default constructor 答:我发布了一段代码,即使用char数组中的placement new。对我来说,这绝对是正常的。但是根据评论,这个代码是错误的。

    有人能更详细地解释一下吗?

    具体来说,数组有什么问题。我从评论中了解到的是 T x[size]; 可能不适合 char x[size*sizeof(T)]; . 我不相信这是真的。

    编辑:

    我只是越来越困惑。我知道在结构的情况下什么是对齐。是的,当您有一个结构时,属性从不同的偏移开始,那么您可能会想。

    好了,现在我们回到数组。你在告诉我 T x [大小]; 和一样大小 char x[尺寸*尺寸(t)] 但是,我不能以T数组的形式访问char数组,因为可能有一些对齐。当数组大小相同时,如何进行对齐?

    编辑2:

    好吧,我终于明白了,可能是从一个错误的地址开始的。

    编辑3:

    每个人,你可以停止发帖:—)哎呀,这个总让我大吃一惊。我只是从未意识到这是可能的。

    5 回复  |  直到 12 年前
        1
  •  13
  •   AnT stands with Russia    14 年前

    T x[size] size * sizeof(T) char buffer[size*sizeof(T)]

    char T malloc new

    int 0x1000 0x1004 0x1001

    size * sizeof(T) + A - 1

        2
  •  0
  •   justin    14 年前

    T

    size_t elementCount;
    // padding to get native alignment for 1st element
    T elements[elementCount];
    

    size_t elementCount; // 4
    char padding[16 - sizeof(elementCount)];
    T elements[elementCount]; // naturally aligned
    

        3
  •  0
  •   Necrolis    14 年前

    char x[size*sizeof(T)]; alignment alignment(2)

        4
  •  0
  •   Steve Jessop    14 年前

    sizeof(int) == 4

    int *intarray = new int[2];        // 8 bytes
    char *charptr = (char *)intarray;  // legal reinterpret_cast
    charptr += 1;                      // still 7 bytes available
    *((int*)charptr) = 1;              // BAD!
    

    int

    char ra[8];
    int *intptr = reinterpret_cast<int*>(ra);
    intptr[0] = 1;  // BAD!
    

    ra

    char ra = new char[8];
    int *intptr = reinterpret_cast<int*>(ra);
    intptr[0] = 1;  // NOT BAD!
    

    new

    struct foo {
        char first[1];
        char second[8];
        char third[3];
    };
    

    second

        5
  •  0
  •   user405725    12 年前

    std::size_t

    alignment