我目前正在阅读内部 C++ 对象模型。在第 9 页,它有一个图表显示了一个类的内容是如何在内存中布局的。它指出对象中实际驻留在类内存中的唯一部分是非静态数据成员。
这是 SO 关于程序内存内容的帖子:
在第二个答案中,它详细说明了程序的内存布局 - 显示了堆栈和堆。
静态数据成员/任何类函数的位置(基本上是类中未存储在对象中的部分——参见第 9 页)是否会根据对象是在堆栈上还是在堆上而改变?
我目前正在阅读内部 C++ 对象模型。在第 9 页,它有一个图表显示了一个类的内容是如何在内存中布局的。它指出对象中实际驻留在类内存中的唯一部分是非静态数据成员。
这是 SO 关于程序内存内容的帖子:
在第二个答案中,它详细说明了程序的内存布局 - 显示了堆栈和堆。
静态数据成员/任何类函数的位置(基本上是类中未存储在对象中的部分——参见第 9 页)是否会根据对象是在堆栈上还是在堆上而改变?
Static data members reside in the same area of memory that global variables and plain static variables would reside. It is the "class memory" that could either be on the stack or heap, depending on how the instance of the class was created.
A static data member is not too different from a global variable. However, it is scoped by the class name, and its access by name can be controlled via public
, private
, and protected
. public
gives access to everyone. private
would restrict access to only members of the class, and protected
is like private
but extends access to a class that inherits from the class with the static data member.
In contrast, a global variable is accessible by name by everyone. A plain static variable is accessible by name by code in the same source file.
A plain class method is actually just a regular function (modulo access controls), but it has an implicit this
parameter. They do not occupy any space in a class. However, a virtual
class method would occupy some memory in the class, since it has to resolve to a derived class's implementation of the method. But, polymorphism is likely not yet covered where you are in your textbook.
No, where variables are allocated doesn't affect the storage of static data or code. These are generally stored in separate memory areas, that are neither stack or heap.
Functions and static data members are special in that that there is only one copy of each in the whole program.
Variables of class, or other, types are most often created and destroyed multiple times during a program run.