sizeof 舍入对齐,但编译器仍将对象放在剩余字节中
Sizeof rounds to the alignment, but the compiler still places objects in the remaining bytes
考虑下面的代码及其输出
#include <cstdint>
#include <iostream>
using std::cout;
using std::endl;
class alignas(8) Something {
std::uint8_t integer{};
};
int main() {
auto something = Something{};
auto character = std::uint8_t{};
cout << sizeof(something) << endl;
cout << reinterpret_cast<std::uintptr_t>(&something) << endl;
cout << reinterpret_cast<std::uintptr_t>(&character) << endl;
}
https://wandbox.org/permlink/m6D0PYWyrGlfjYJP。单个 运行
的输出
8
140729604143976
140729604143975
如果我有一个按 8 字节对齐的结构,对其调用 sizeof
会将结构的大小四舍五入为其对齐的最接近倍数。但是编译器仍然能够将对象放置在舍入大小留下的假设 space 中。
在什么情况下允许这样做?总是允许吗?如果不遵守,为什么 sizeof
将这里的大小四舍五入?
它位于 something
处 140729604143976
即 0x7FFE2A107B68
它位于 character
处 140729604143975
即 0x7FFE2A107B67
注意character
在内存中something
字节之前,因此是有效的。 something
从 0x7FFE2A107B68
到 0x7FFE2A107B70
并且完全不与 character
重叠。
考虑下面的代码及其输出
#include <cstdint>
#include <iostream>
using std::cout;
using std::endl;
class alignas(8) Something {
std::uint8_t integer{};
};
int main() {
auto something = Something{};
auto character = std::uint8_t{};
cout << sizeof(something) << endl;
cout << reinterpret_cast<std::uintptr_t>(&something) << endl;
cout << reinterpret_cast<std::uintptr_t>(&character) << endl;
}
https://wandbox.org/permlink/m6D0PYWyrGlfjYJP。单个 运行
的输出8
140729604143976
140729604143975
如果我有一个按 8 字节对齐的结构,对其调用 sizeof
会将结构的大小四舍五入为其对齐的最接近倍数。但是编译器仍然能够将对象放置在舍入大小留下的假设 space 中。
在什么情况下允许这样做?总是允许吗?如果不遵守,为什么 sizeof
将这里的大小四舍五入?
它位于 something
处 140729604143976
即 0x7FFE2A107B68
它位于 character
处 140729604143975
即 0x7FFE2A107B67
注意character
在内存中something
字节之前,因此是有效的。 something
从 0x7FFE2A107B68
到 0x7FFE2A107B70
并且完全不与 character
重叠。