C++类和对象 - 内存

发布于 2024-10-14 15:47:21 字数 70 浏览 2 评论 0原文

对象哪个占用内存?而且,是在编译时还是执行时?

谢谢。

Whcih occupies memory, a class or an object? And, is that at compile or execution time?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

沙与沫 2024-10-21 15:47:21

在编译期间,内存布局是一个实现细节——您不需要知道或关心。

然而,在运行时期间...在 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.

念﹏祤嫣 2024-10-21 15:47:21

对象实例是在执行时占用内存的实例,因为是对象的蓝图。

另外,C++中还有静态变量、局部变量和全局变量,它们也占用内存。

The object instance is the one which occupies memory at execution time since a class is the blueprint of the object.

Also, in C++ there are static variables, local variables and global variables which also occupies memory.

只为一人 2024-10-21 15:47:21

静态、局部和全局变量存储在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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文