对齐方式与指针中尾随零的数量有何关系
How is alignment related to the number of trailing zeros in a pointer?
我试图了解记忆对齐在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)
位。
相关文章:
- C++GTKMM gui循环依赖关系
- this_thread::sleep_for和计时时钟之间的关系是否由C++11标准指定
- Doxygen - 如何在不生成图形的情况下生成文本调用关系结果
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 在 c++ 中对字符串进行操作的关系运算符无法按预期工作
- 如何记住这种递归关系?
- 如何在头文件中声明类模板(由于循环依赖关系)
- 移动语义和深层/浅层复制之间有什么关系?
- 如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
- 对在不同二进制文件中创建的对象文件的依赖关系
- #include < conio.h> 和 getch() 方法之间的关系是什么?
- 使用Bazel构建具有不同编译器/链接器选项的C/C++依赖关系
- OpenVINO - 推理库插件 libMKLDNNPlugin.so 无法解析依赖关系
- 模拟测试中类的依赖关系
- 关于记忆后这种递归关系的时间复杂度
- C++模板方法中的循环依赖关系
- 什么是GCC和MingW,它们与C 有何关系
- 对齐方式与指针中尾随零的数量有何关系
- 垃圾回收的概念与非 OOP 语言有何关系
- 缺少复制构造函数与对象切片有何关系