数据成员是否与 C++ 中的对象分配在相同的内存空间中?

2021-12-24 00:00:00 memory-management c++

假设我有一个这样的课程:

Say I've got a class like this:

class Test
{
  int x;
  SomeClass s;
}

我像这样实例化它:

Test* t = new Test;

x 是在栈上还是堆上?s呢?

Is x on the stack, or the heap? What about s?

推荐答案

每次实例化"时一个使用 new 的对象/符号(我们在这里说的是 C++),将为这个对象分配一个新的内存区域.如果没有,它将被放在本地"上.内存区.

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 是通过一个 new 分配的,因此,在堆上.

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 是一个指针,用 new 分配,aa01::c 设计的对象在堆上,在另一个内存范围内而不是分配给 aa01.

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 - 什么是本地"?研究对象的内存:堆堆栈?
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.

相关文章