使用__declspec的内存填充问题
Memory padding issues using __declspec
基于MSDN的__declspec(align(x))应该在成员变量之后添加x位填充,例如:
#include <iostream>
using namespace std;
void main()
{
struct test
{
__declspec(align(32))char x;
__declspec(align(32))int i;
__declspec(align(32)) char j;
};
cout << sizeof(test) << endl;//will print 96 which is correct
}
现在考虑以下情况:
#include <iostream>
using namespace std;
void main()
{
struct test
{
char x;
int i;
char j;
};
cout << sizeof(test) << endl;//will print 12
//1 byte for x + 3 bytes padding + 4 bytes for i + 1 byte for j +3 bytes padding =12
}
但是如果我把代码改成:
#include <iostream>
using namespace std;
void main()
{
struct test
{
char x;
int i;
__declspec(align(1)) char j;
};
cout << sizeof(test) << endl;//will print 12 again!!!!
}
为什么它给我12而不是9!我告诉编译器我不希望j.
__declspec(align(1)) char j
不做任何事情- char
不需要与__declspec
进行特殊对齐。
假设您稍后声明了一个test
: test arr[2];
数组。这里,arr[0].i
和arr[1].i
必须在4字节边界上对齐;要求sizeof(arr[0])
是4的倍数。
相关文章:
- C++ 填充数组时遇到问题
- 将十六进制值设置为用于填充的字符变量时出现问题
- 我想直接在结构中插入,但没有一种方法可以正确避免填充问题
- 使用初始化列表填充C++中的多维结构数组时出现问题
- 使用队列和列表 STL 进行C++分配。在将数据填充到列表或队列中然后打印该数据时遇到问题
- 在使用结构体和用函数填充其变量(使用指针)时遇到问题
- 用零填充矩阵行的问题
- BMP文件行填充问题
- 按行、列或随机从数组填充矩阵时出现错误索引问题
- 清除并重新填充 std::vector<std::vector<T>>导致分配问题
- 填充 c++ 数组时遇到问题,每个索引处只有最后一项
- 尝试递归填充和打印出两组的所有归纳函数的问题
- 这个简单的木炭填充器有什么问题
- 在检查现有元素时,从文件填充并行数组时出现问题
- 填充动态类模板数组时遇到问题
- 使用__declspec的内存填充问题
- 使用 C++11 的 std::regex 填充子匹配时遇到问题
- 长哈希填充问题
- 内存填充问题
- 简单的结构对齐/填充问题