对齐方式与指针中尾随零的数量有何关系

How is alignment related to the number of trailing zeros in a pointer?

本文关键字:何关系 关系 指针 方式 对齐      更新时间:2023-10-16

我试图了解记忆对齐在C++中的工作原理。

如果我理解正确,如果指针的二进制表示中的尾随零数n则指针对齐为 2^n 字节。但是,以下程序:

#include <bitset>
#include <cstdint>
#include <iostream>
#include <climits>
#include <cassert>
template <typename T>
std::size_t nTrailingZeros(const T* pointer)
{
    assert(CHAR_BIT == 8);
    std::bitset<8*sizeof(std::uintptr_t)> bits(reinterpret_cast<std::uintptr_t>(pointer));
    std::size_t nZeroes{};
    while (nZeroes < bits.size() && !bits[nZeroes])
    {
        ++nZeroes;
    }
    return nZeroes;
}
struct alignas(64) A {int x;};
int main()
{
    std::cout << "Alignment: "      << alignof (A)            << std::endl;
    std::cout << "Trailing zeros: " << nTrailingZeros (new A) << std::endl;
} 

输出:

对齐方式:64 尾随零:4

在我的电脑上。

我做错了什么?我希望至少有 6 个尾随零,但我只得到 4 个(建议 16 字节对齐)。

不支持为过度对齐的数据分配动态内存。这很不幸,但你必须自己获得对齐的内存,然后重新放置到其中。

旁注:您的bitset不够大。你想要8*sizeof (uintptr_t)位。