本文介绍了对象在内存中看起来像什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





可能是一个真正蠢的问题,但我会问。我很好奇内存中的对象看起来像什么。显然,它必须有它的所有成员数据。我假设一个对象的函数不会在内存中重复(或者我错了?)。在内存中拥有999个对象,所有的对象都具有相同的函数。如果所有999个对象在内存中只有一个函数,那么每个函数如何知道要修改哪个成员数据(我特别想在低级别上知道)。有一个对象指针被发送到幕后的函数吗?也许每个编译器都不一样?

This is probably a really dumb question, but I will ask anyway. I am curious what an object looks like in memory. Obviously it would have to have all of its member data in it. I assume that functions for an object would not be duplicated in memory (or maybe I am wrong?). It would seem wasteful to have 999 objects in memory all with the same function defined over and over. If there is only 1 function in memory for all 999 objects, then how does each function know who's member data to modify (I specifically want to know at the low level). Is there an object pointer that gets sent to the function behind the scenes? Perhaps it is different for every compiler?

此外,static关键字如何影响这一点?使用静态成员数据,我认为所有999个对象将使用完全相同的内存位置作为其静态成员数据。这在哪里存储?静态函数我想也只是在内存中的一个地方,不必与实例化的对象交互,我认为我理解。

Also, how does the static keyword affect this? With static member data, I would think that all 999 objects would use the exact same memory location for their static member data. Where does this get stored? Static functions I guess would also just be one place in memory, and would not have to interact with instantiated objects, which I think I understand.

推荐答案

静态类成员几乎完全像全局变量/函数一样处理。因为它们没有绑定到实例,所以没有什么可以讨论内存布局。

Static class members are treated almost exactly like global variables / functions. Because they are not tied to an instance, there is nothing to discuss regarding memory layout.

类成员变量可以想象,因为每个实例对于每个成员变量都可以有自己的唯一值。

Class member variables are duplicated for each instance as you can imagine, as each instance can have its own unique values for every member variable.

类成员函数在代码段中只存在一次记忆。在低级别,他们就像正常的全局函数,但他们收到的指针。使用Visual Studio on x86,它通过 ecx 使用调用约定。

Class member functions only exist once in a code segment in memory. At a low level, they are just like normal global functions but they receive a pointer to this. With Visual Studio on x86, it's via ecx register using thiscall calling convention.

当谈到虚函数,多态性时,内存布局变得更加复杂, ,它基本上是一组定义类实例的地形的函数指针。

When talking about virtual functions, polymorphism, then the memory layout gets more complicated, introducing a "vtable" which is basically a bunch of function pointers that define the topography of the class instance.

这篇关于对象在内存中看起来像什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 21:10