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

查看:78
本文介绍了如何确定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 | etc |为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.

最后,访问说明符(公共,私有,受保护)授予编译器一定的回旋余地,以打包数据成员.

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天全站免登陆