如何确定C ++中对象的大小? [英] How do you determine the size of an object in C++ ?

查看:218
本文介绍了如何确定C ++中对象的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,假设我有一个类Temp:

For example, say I have a class Temp:

class Temp
{
public:
int function1(int foo) { return 1; }
void function2(int bar) { foobar = bar; }

private:
int foobar;
};

当我创建一个Temp类的对象时,我如何计算它需要多少空间,它在内存中表示(例如| foobar为| 4字节| function1 |等|为8字节)

When I create an object of class Temp, how would I calculate how much space it needs, and how is it represented in memory (e.g.| 4 bytes for foobar| 8 bytes for function1 | etc | )

推荐答案

近似,对象的大小是其组成数据成员的大小的总和。您可以确定它不会小于此值。

To a first order approximation, the size of an object is the sum of the sizes of its constituent data members. You can be sure it will never be smaller than this.

更准确地说,编译器有权在数据成员之间插入填充空间,以确保每个数据成员满足对齐平台的要求。一些平台对于对齐非常严格,而其他(x86)是更宽容,但将执行明显更好与正确对齐。因此,即使编译器优化设置也会影响对象大小。

More precisely, the compiler is entitled to insert padding space between data members to ensure that each data member meets the alignment requirements of the platform. Some platforms are very strict about alignment, while others (x86) are more forgiving, but will perform significantly better with proper alignment. So, even the compiler optimization setting can affect the object size.

继承和虚函数增加了额外的复杂性。正如其他人所说,类的成员函数本身并不占用每个对象空间,但是在该类的接口中存在虚拟函数通常意味着虚拟表的存在,基本上是一个函数指针的查找表,用于动态地解析在运行时调用的适当的函数实现。通常通过存储在每个对象中的指针访问虚拟表(vtbl)。

Inheritance and virtual functions add an additional complication. As others have said, the member functions of your class themselves do not take up "per object" space, but the existence of virtual functions in that class's interface generally implies the existence of a virtual table, essentially a lookup table of function pointers used to dynamically resolve the proper function implementation to call at runtime. The virtual table (vtbl) is accessed generally via a pointer stored in each object.

派生类对象还包括其基类的所有数据成员。

Derived class objects also include all data members of their base classes.

最后,访问说明符(public,private,protected)允许编译器在数据成员打包时有一定的余地。

Finally, access specifiers (public, private, protected) grant the compiler certain leeway with packing of data members.

是sizeof(myObj)或sizeof(MyClass)将总是告诉你一个对象的正确大小,但其结果并不总是容易预测。

The short answer is that sizeof(myObj) or sizeof(MyClass) will always tell you the proper size of an object, but its result is not always easy to predict.

这篇关于如何确定C ++中对象的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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