Mar*_*dik 2 c++ memory-alignment c++11
我试图了解内存对齐在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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
对齐:64尾随零:4
在我的电脑上.
我究竟做错了什么?我期望至少6个尾随零,但我只得到4(建议16字节对齐).
不支持过度对齐数据的动态内存分配.这很不幸,但你必须自己获得对齐的记忆,然后将其置于新的位置.
旁注:你bitset的不够大.你想要8*sizeof (uintptr_t)比特.