【问题标题】:Alignment of struct in a linear allocator线性分配器中结构的对齐
【发布时间】:2021-07-11 23:13:52
【问题描述】:

我正在 x64 上为此类构建一个非常简单的线性分配器:

class Test {
    size_t first[64];    // 512 bytes
    void* second[64];    // 512 bytes
    unsigned char third; // 1 byte
};

Test 的总大小应该是 1025 字节,但它的实际大小是 1032 字节,这是预期的。编译器已经自动对齐了结构,很好。

现在这里是我的线性分配器的准系统:

class Allocator {
private:
    Test* memory;
public:
    Allocator(const size_t size) {
        memory = static_cast<Test*>(malloc(sizeof(Test) * size));
    }
    Test* allocate() {
        return memory++;
    }
};

而且效果很好!

但是,我看到许多其他简单的线性分配器在 allocate 函数中对齐内存。他们为什么这样做呢? Test 结构本身已经对齐。

另外,如果你决定使用某种对齐方式,你会在分配内存时对齐内存吗?或者你会在allocate 函数中返回一个对齐的指针吗? 另外,您会将其与sizeof(Test) 或平台的WORD 大小对齐吗?

【问题讨论】:

    标签: c++ memory alignment


    【解决方案1】:
    1. many other simple linear allocators align the memory in the allocate function. Why do they do this? 如果他们需要不同的对齐方式,例如 16 或 32 字节(用于 AVX),他们会这样做。

    2. if you do align the newly allocated memory, would you align the memory when you allocate it? Or would you align it when you return the memory block?你不能重新对齐已经分配的内存。

    3. Also, would you align it to the sizeof(Test), or the platform's WORD size? 取决于您对齐的原因。

    【讨论】:

    • 对于#2,我的意思是例如调用aligned_alloc 来分配而不是malloc,然后在allocate 函数中,您将手动对齐内存以返回。
    • 另外,我正在调整性能,因为我将进行许多分配。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2015-05-17
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    相关资源
    最近更新 更多