我最近看到我的一位同事做了类似的事情:
#include <iostream>
class myClass
{
public:
float X, Y;
myClass(int x, int y) : X(x), Y(y){}
};
int main()
{
char buffer[1024] = { 0 };
myClass example(12, 24);
memcpy(buffer, &example.X, sizeof(float) * 2); // Is this safe? Will X always be allocated next o Y?
}
基本上,他试图通过告诉内存副本读取两倍大小的浮点数来一步将 theX
和 the复制Y
到全部中。char[]
它肯定可以正常工作,我认为这很酷并继续前进。但是由于 C++ 中所有未定义的行为。我想知道这是否保证始终有效。Y 总是在 X 之后被分配吗?