| |
 | Posted by matheus in reply to Paul | Permalink Reply |
|
matheus 
| On Sunday, 1 January 2023 at 09:01:24 UTC, Paul wrote:
> ...
> If the size of MyClass is 9 bytes why do MyClassO1 & O2 addresses only differ by 4 bytes?
>
> Because those addresses(4FFB20 4FFB24) are the addresses of the class **variables**, not the addresses of the **objects** themselves?
Because MyClass01 and MyClass02 are pointers and in your case they differ 4 bytes each other.
Now you could do this:
import std.stdio, std.traits;
class MyClass {char[16] c;}
void main() {
writeln(" Size Alignment Type\n",
"=========================");
size_t size = __traits(classInstanceSize, MyClass);
size_t alignment = classInstanceAlignment!MyClass;
writefln("%4s%8s %s",size, alignment, MyClass.stringof);
// my test code added
MyClass MyClassO1;
MyClass MyClassO2;
writeln("\n",&MyClassO1,"\t",&MyClassO2);
writeln("\n",&(MyClassO1.c),"\t",&(MyClassO2.c));
MyClassO1 = new MyClass();
MyClassO2 = new MyClass();
writeln("\n",&MyClassO1,"\t",&MyClassO2);
writeln("\n",&(MyClassO1.c),"\t",&(MyClassO2.c));
}
In this machine it will print:
Size Alignment Type
=========================
32 8 MyClass
7FFD890C6410 7FFD890C6418 <- &MyClassO1 &MyClassO2
10 10 <- Note here [&(MyClassO1.c), &(MyClassO2.c)]
7FFD890C6410 7FFD890C6418 <- &MyClassO1 &MyClassO2 (Same address)
7FD0435D8010 7FD0435D8030 <- Now after instantiation! [&(MyClassO1.c), &(MyClassO2.c)]
Finally as you can see I changed your:
class MyClass {char c;}
to:
class MyClass {char[16] c;}
Because from char[1] to char[16] it will keep the address difference for [&(MyClassO1.c), &(MyClassO2.c)] by 0x20 (32):
7FD0435D8010 7FD0435D8030
If I change to char[17]
The difference goes up from 0x20 (32) to 0x30 (48), and keeps that way until char[32]:
7FD0435D8010 7FD0435D8040
char[33] will increase again by 16 bytes and so on.
Matheus.
|