sizeof(value)vs sizeof(type)? [英] sizeof(value) vs sizeof(type)?

查看:139
本文介绍了sizeof(value)vs sizeof(type)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

double data; 
double array[10]; 
std::vector<int> vec(4, 100); 
MyClass myclass;   

之间是否存在差异:

sizeof(double);
sizeof(double[10]);
sizeof(std::vector<int>);
sizeof(MyClass);

sizeof(data);
sizeof(array);
sizeof(vec);
sizeof(myclass);

这两种语法是否不同或严格等效?是否在编译时都对它们进行了评估?如果不是,则在运行时评估哪个?

Are the two syntaxes different or strictly equivalent ? Are all of them evaluated at compile-time ? If not, which one is evaluated at run-time ?

推荐答案

唯一的区别在于语法和方便性。

The only differences are in syntax and convenience.

从语法上讲,在一种情况下,您可以省略括号,但在另一种情况下则不允许:

Syntactically, you're allowed to leave out the parentheses in one case, but not the other:

double d;

sizeof(double); // compiles
sizeof(d);      // compiles
sizeof d;       // compiles
sizeof double;  // does NOT compile

就方便程度而言,请考虑以下内容:

As far as convenience goes, consider something like:

float a;

x = sizeof(float);

y = sizeof(a);

例如,如果某个时候您最终更改了 a float 变为双精度,您还需要将 sizeof(float)更改为 sizeof(double)进行匹配。如果您始终使用 sizeof(a),则当您从 float更改 a 时, code>到 double ,您对 sizeof 的所有使用也会自动更改,而无需进行任何编辑。后者比C ++在C语言中更常见,例如在调用malloc时:

If, for example, you sometime end up changing a from a float to a double, you'd also need to change sizeof(float) to sizeof(double) to match. If you use sizeof(a) throughout, when you change a from a float to a double, all your uses of sizeof will automatically change too, without any editing. The latter is more often a problem in C than C++, such as when calling malloc:

float *a = malloc(10 * sizeof(float));

vs。

float *a = malloc(10 * sizeof(*a));

在第一种情况下,更改第一个 float double 将产生可编译的代码,但有缓冲区溢出。在第二种情况下,将(仅) float 更改为 double 可以正常工作。

In the first case, changing the first float to double will produce code that compiles, but has a buffer overrun. In the second case, changing the (only) float to double works fine.

这篇关于sizeof(value)vs sizeof(type)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆