对象创建在堆栈/堆? [英] Object creation on the stack/heap?

查看:189
本文介绍了对象创建在堆栈/堆?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码在堆栈上创建一个对象:

The following code creates an object on the stack:

Object o;

在堆上创建对象时,我们可以使用:

When creating an object on the heap we can use:

Object* o;

o = new Object();

而不是:

Object* o = new Object();

当我们将堆对象创建分成两行并调用第二行的构造函数code> o = new object()),这意味着在第一行( Object * o 堆栈?因此 Object o 将对象放在堆栈上,而 Object * o 将指针指向堆栈上的未来对象?

When we split the heap object-creation over two lines and call the constructor on the second line (o = new object()), does this mean in the first line (Object* o) the pointer was created on the stack? So Object o puts the object on the stack, whereas Object* o puts the pointer to a future object on the stack?

我的第二个问题涉及如果两行代码在类外调用。我最近阅读过( C中的全局内存管理堆栈或堆)吗? )全局变量不包含在堆栈/堆中,但实际上是内存的另一部分?如果是这种情况, Object * o 创建一个指针,它将位于内存的这个其他部分,它指向堆对象?

My second question involves if the two lines of code were called outside of a class. I recently read (Global memory management in C in stack or heap?) that global variables are not contained on the stack/heap but actually another part of memory? If this is the case, would Object* o create a pointer which would sit in this other part of the memory and it points to the heap object?

推荐答案

实际上,两个语句都不说堆或堆栈:

Actually, neither statement says anything about heap or stack:

Object o;

使用自动存储创建对象,意味着存储位置由声明对象的上下文:如果代码在一个函数中,这恰好是调用堆栈。但是该行也可以是类成员,或者正如你所说的,在一个函数/类之外。

creates an object with automatic storage meaning that the storage location is determined by the context in which the object is declared: If the code is in a function, this happens to be the call stack. But the line could also be a class member or, as you’ve noted, outside of a function / class.

为了说明为什么这是不同的:

To illustrate why this is different:

struct Foo {
    Object o;
};

Foo* pf = new Foo();

现在对象 pf-> o 是在堆上创建的,而不是在堆栈上,即使(或者因为)它有自动存储。

Now the object pf->o is created on the heap, not on the stack, even though (or rather, because) it has automatic storage.

相反,

Object* p;

只是声明一个指针,没有更多。 指针的存储空间与任何其他对象的存储空间无法区分:它具有自动存储。此外,初始化表达式对变量存储没有影响。

simply declares a pointer, nothing more. The pointer’s storage is indistinguishable from any other object’s: it has automatic storage. Furthermore, the initialising expression has no effect on the variable storage.

指针指向的是一个完全不同的事情。它可能是一个堆分配的对象(例如使用 new ),也可能指向另一个自动分配的对象。考虑:

What the pointer points to is a completely different matter. It might be a heap-allocated object (using new for instance) or it might point to another automatically allocated object. Consider:

Object o;
Object* p = &o;

这篇关于对象创建在堆栈/堆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆