获取成员变量的大小 [英] Getting the size of member variable

查看:116
本文介绍了获取成员变量的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果存在 POD 结构,并包含一些成员变量,例如:

If there is a POD structure, with some member variables, for example like this:

struct foo
{
   short a;
   int b;
   char c[50];
   // ...
};

有一种方法可以获取成员变量的大小,类型?

Is there a way to get the size of a member variable in bytes, without creating an object of this type?

我知道这将工作:

foo fooObj;
std::cout << sizeof( fooObj.a ) << std::endl;
std::cout << sizeof( fooObj.b ) << std::endl;
std::cout << sizeof( fooObj.c ) << std::endl;

编译器会优化以下内容并防止构造对象?

Would the following be optimized by the compiler and prevent the construction of an object?

std::cout << sizeof( foo().a ) << std::endl;


推荐答案

5.3.3 / 1:

5.3.3/1:


sizeof运算符产生其操作数的对象表示
中的字节数
。操作数是
表达式,未评估
或括号类型ID。

The sizeof operator yields the number of bytes in the object representation of its operand. The operand is either an expression, which is not evaluated, or a parenthesized type-id.

上面的意思是下面的结构是很好定义的:

The above means the following construct is well defined:

sizeof( ((foo *) 0)->a);

这篇关于获取成员变量的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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