问题描述
例如,假设我有一个 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 个字节 | etc | )
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++ 中如何确定对象的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!