Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof operator & alignment in C++ vs D

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.

like image 237
Destructor Avatar asked Feb 07 '23 18:02

Destructor


1 Answers

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
like image 113
Vladimir Panteleev Avatar answered Feb 16 '23 02:02

Vladimir Panteleev