2
私はメモリアライメントがC++でどのように機能するかを理解しようとしています。アライメントは、ポインタ内の末尾のゼロの数とどのように関連していますか?
正しく理解すれば、n
がポインタのバイナリ表現の末尾の0の数であれば、ポインタは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バイトのアライメントを示唆しています)。
*まだ*サポートされていません。 C++ 17はこの穴を塞ぎます。 –