C++类和对象 - 内存
类
和对象
哪个占用内存?而且,是在编译时还是执行时?
谢谢。
Whcih occupies memory, a class
or an object
? And, is that at compile
or execution
time?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在编译期间,内存布局是一个实现细节——您不需要知道或关心。
然而,在运行时期间...在 C++ 中,类定义类型,但(除非您激活 RTTI,它允许对类进行有限的内省)本身通常不占用任何内存1——它们只是框架用于物体的建造和破坏。然而,它们的方法(构造函数、析构函数、实例方法和类方法)占用了可执行内存的一部分,但编译器可以并且确实优化了程序中未使用的任何此类方法。
类型的实例(即对象以及像
int
变量这样的基元)占用了 C++ 中的大部分内存,但对于它们的成员函数,它们引用回它们的类。特定类的实例到底使用了多少内存完全是一个实现细节,您通常不需要关心它。1 即使如此,类本身也不使用内存,但其关联的
std::typeinfo
实例却使用内存。但同样,这通常是实现的东西,即使是枯燥的程序员也不会非常关注。During compilation, the layout of memory is an implementation detail--you don't need to know or care.
During runtime, however... in C++, classes define types but (unless you activate RTTI which allows limited introspection into classes) don't generally occupy any memory themselves1--they're just the frameworks for the construction and destruction of objects. Their methods, however--the constructors, destructors, instance methods, and class methods, occupy some portion of executable memory, but compilers can and do optimize away any such methods that are not used in the program.
Instances of types (that is, objects as well as primitives like
int
variables) occupy the bulk of memory in C++, but for their member functions they refer back to their classes. Exactly how much memory an instance of a particular class uses is entirely and utterly an implementation detail, and you should generally not need to care about it.1 Even then, the classes themselves don't use the memory, but their associated
std::typeinfo
instance does. But again, this is generally implementation-y stuff and not the sort of thing even wizened programmers pay much attention to.对象实例
是在执行时占用内存的实例,因为类
是对象的蓝图。另外,C++中还有静态变量、局部变量和全局变量,它们也占用内存。
The
object instance
is the one which occupies memory at execution time since aclass
is the blueprint of the object.Also, in C++ there are static variables, local variables and global variables which also occupies memory.
静态、局部和全局变量存储在BBS数据段中,而对象存储在堆或堆栈中。
对象是类的实例,而类定义由编译器使用它的类描述来创建对象。类就像是一条“如何自己建桌子”的指令,只占据它所写的纸,而对象则是你自己根据指令制作的真正的桌子,占据了真实的空间。
Static, local and global variables are stored in BBS data segment, while objects are stored either in heap or in stack.
Objects are the instances of class, while class definition is used by compiler to create an object by it's class description. Class is like an instruction of "how to build table by yourself" that occupies only the paper it's written on, while an object is the real table made by yourself according to the instruction, that occupies the real space.