此常见问题解答涉及聚合和POD,并涵盖以下材料:
是否有关于元组伪成员的布局和内存对齐的正式规范?
反正有没有修改元组中类型的内存对齐?它是否受#pragma pack()指令的影响?
例如:
typedef std::tuple<uint8_t, uint32_t> myTuple;
Run Code Online (Sandbox Code Playgroud)
是否有任何规范说这将在内存中与以下相同:
#pragma pack() // Default packing
struct myStruct
{
uint8_t first;
uint32_t second;
}
Run Code Online (Sandbox Code Playgroud)
抱歉,如果这是一个愚蠢的问题,但我不完全理解模板的对齐.
编辑:我正在努力完成的例子
目前我有一些东西......
#pragma pack(push)
#pragma pack(4)
struct cTriangle
{
uint32 Index[3];
};
#pragma pack(pop)
template <class T>
inline bool Read(cFileStream& fStream, std::vector<T>& vec)
{
if (!vec.size())
return true;
// fStream.Read(void* pBuffer, size_t Size)
// Just a wrapper around a binary ifstream really
return fStream.Read(&vec[0], sizeof(T) * vec.size());
}
std::vector<cVector3> vPoint;
vPoint.resize(Verticies);
bool result = Read(FileStream, vPoint);
Run Code Online (Sandbox Code Playgroud)
如果我想为元编程目的使用typedef …
我用gcc和g ++编译了这个迂腐,我不会在任何一个中得到警告:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct a {
struct a *next;
int i;
};
struct b {
struct b *next;
int i;
};
struct c {
int x, x2, x3;
union {
struct a a;
struct b b;
} u;
};
void foo(struct b *bar) {
bar->next->i = 9;
return;
}
int main(int argc, char *argv[]) {
struct c c;
memset(&c, 0, sizeof c);
c.u.a.next = (struct a *)calloc(1, sizeof(struct a));
foo(&c.u.b);
printf("%d\n", c.u.a.next->i);
return 0;
} …Run Code Online (Sandbox Code Playgroud)