简体   繁体   English

C ++与D中的sizeof运算符和对齐

[英]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. 由于对齐,它将输出8作为预期。 C++ Compiler adds padding of 3 bytes. C ++编译器添加3个字节的填充。 But If I do the same in D language it gives me completely unexpected output. 但如果我用D语言做同样的事情,它会给我完全意想不到的输出。 (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 ? sizeof(T)是多少? I was expecting to get 8 as an output of class' size. 我期望得到8作为班级规模的输出。 How D compiler performs alignment here? D编译器如何在这里执行对齐? Am I understading wrong something ? 我错了什么吗? I am using Windows 7 32 bit OS & Dmd compiler. 我正在使用Windows 7 32位OS和Dmd编译器。

Classes in D are reference types (ie they work like in Java or C#). D中的类是引用类型(即它们的工作方式类似于Java或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). 当你声明一个T类型的变量(其中T是一个类)时,你只是声明一个类引用(默认情况下为null ),它将指向实际类的数据( char cint i在你的例)。 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). 因此, T.sizeof仅测量引用的大小,该大小将等于指针大小(4的结果仅表示您的目标是32位平台)。

Try declaring T as a struct : 尝试将T声明为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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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