简体   繁体   中英

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.

Classes in D are reference types (ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM