Why is the memory of a global structure and a member variable (of the same type) set equal to the global different?
I am constructing an object like so:
TestObj::TestObj(const TypedefStruct& myStruct) : m_memberStruct(myStruct){}
The struct looks like this:
typedef struct{ short x; short y;} TypedefStruct;
. it is a public member of class TestObj
.`
When I compare the memory of the global myStruct
being passed into the constructor and the m_memberStruct
member variable of TestObj
, the memory contents differ.
PS: I am initializing the global struct like so: TestObj::TypeDefStruct myStruct = {0};
I have read that compilers will sometimes pad the elements of a struct to make each element the same size, and that that can interfere with comparing the memory of a global struct 开发者_如何学运维and a "copy" of it, but I don't think that applies here because it is a same-type two-element struct...
Any insight on the situation? If I cannot actually compare the memory besides just checking the values of the two elements I would still like to understand why the memory contents are different.
The compiler can pad m_memberStruct because it is part of TestObj. That is, it may try to give TestObj proper alignment.
Are you sure you are looking at the data and not say the addresses of the objects?
You could try initializing the variables to easily recognized values and then looking:
myStruct.x = 0xAA;
myStruct.y = 0xBB;
精彩评论