Consider following program:
#include <iostream>
class T {
char c;
int i;
};
int main() {
std::cout<<sizeof(T)<<'\n';
}
It gives output 8
as an expected because of alignment. C++ Compiler adds padding of 3 bytes. But If I do the same in D language it gives me completely unexpected output. (See live demo here.)
import std.stdio;
class T {
char c;
int i;
}
int main() {
writefln("sizeof T is %d",T.sizeof);
writefln("sizeof char is %d",char.sizeof);
writefln("sizeof int is %d",int.sizeof);
return 0;
}
The output I get is:
sizeof T is 4
sizeof char is 1
sizeof int is 4
How sizeof(T)
is 4 ? I was expecting to get 8
as an output of class' size. How D compiler performs alignment here? Am I understading wrong something ? I am using Windows 7 32 bit OS & Dmd compiler.
Classes in D are reference types (i.e. they work like in Java or C#). When you declare a variable of type T
(where T
is a class), you're only declaring a class reference (which will be null
by default), which will point to the actual class's data (the char c
and int i
in your example). Thus, T.sizeof
only measures the size of the reference, which will be equal to the pointer size (a result of 4 only indicates that you're targeting a 32-bit platform).
Try declaring T
as a struct
:
import std.stdio;
struct T {
char c;
int i;
}
int main() {
writefln("sizeof T is %d",T.sizeof);
writefln("sizeof char is %d",char.sizeof);
writefln("sizeof int is %d",int.sizeof);
return 0;
}
On my machine, the above outputs:
sizeof T is 8
sizeof char is 1
sizeof int is 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With