数据成员是否在与C ++中的对象相同的内存空间中分配? [英] Are data members allocated in the same memory space as their objects in C++?
问题描述
说我有这样的类:
class Test
{
int x;
SomeClass s;
}
我像这样实例化:
Test* t = new Test;
堆栈上是x还是堆?
推荐答案
每次你使用一个新的实例化一个对象/符号将为此对象分配一个新的内存区域。
Each time you "instantiate" an object/symbol using a new (we are speaking C++ here), a new memory zone will be allocated for this object. If not, it will be put on the "local" memory zone.
问题是我没有本地内存区域的标准定义。
The problem is that I have no standard definition for "local" memory zone.
这意味着,例如:
struct A
{
A()
{
c = new C() ;
}
B b ;
C * c ;
}
void doSomething()
{
A aa00 ;
A * aa01 = new A() ;
}
对象aa00分配在堆栈上。
The object aa00 is allocated on the stack.
由于aa00 :: b根据aa00分配在本地存储器上,所以aa00 :: b分配在由新的aa01指令分配的存储器范围内。因此,aa00 :: b也在堆栈上分配。
As aa00::b is allocated on a "local" memory according to aa00, aa00::b is allocated inside the memory range allocated by the new aa01 instruction. Thus, aa00::b is also allocated on stack.
但aa00 :: c是一个指针,分配有new,所以由aa00 :: c设计的对象
But aa00::c is a pointer, allocated with new, so the object designed by aa00::c is on the heap.
现在,一个棘手的例子:aa01是通过一个新的分配,因此,在堆上。
Now, the tricky example: aa01 is allocated via a new, and as such, on the heap.
在这种情况下,由于aa01 :: b根据aa01分配在本地存储器上,aa00 :: b分配在由新的aa01指令分配的存储器范围内。因此,aa00 :: b在堆上,内部已经为aa01分配的内存。
In that case, as aa01::b is allocated on a "local" memory according to aa01, aa00::b is allocated inside the memory range allocated by the new aa01 instruction. Thus, aa00::b is on the heap, "inside" the memory already allocated for aa01.
由于aa01 :: c是一个指针,
As aa01::c is a pointer, allocated with new, the object designed by aa01::c is on the heap, in another memory range than the one allocated for aa01.
所以,游戏的点是:
1 - 被研究对象的本地内存是什么:Stack of Heap?
2 - 如果对象是通过new分配,那么它在这个本地内存之外,即它在堆上的其他地方
3 - 如果对象被分配没有新,则它在本地内存中。
4 - 如果本地内存在堆栈上,则分配的没有new的对象也在堆栈上。
5 - 如果本地内存在堆上,那么分配的没有new的对象也在堆上,但仍在本地内存中。
So, the point of the game is:
1 - What's the "local" memory of the studied object: Stack of Heap?
2 - if the object is allocated through new, then it is outside this local memory, i.e., it is elsewhere on the heap
3 - if the object is allocated "without new", then it is inside the local memory.
4 - If the "local" memory is on the stack, then the object allocated without new is on the stack, too.
5 - If the "local" memory is on the heap, then the object allocated without new is on the heap, too, but still inside the local memory.
对不起,我没有更好的词汇来表达这些概念。
Sorry, I have no better vocabulary to express those concepts.
这篇关于数据成员是否在与C ++中的对象相同的内存空间中分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!