C ++中的指针存储在堆栈或堆中的什么位置? [英] Where are pointers in C++ stored, on the stack or in the heap?

查看:274
本文介绍了C ++中的指针存储在堆栈或堆中的什么位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解堆栈内存之间的区别,以及 很好地解释了基础知识.

I am trying to understand the difference between the stack and heap memory, and this question on SO as well as this explanation did a pretty good job explaining the basics.

但是,在第二种解释中,我遇到了一个我有一个具体问题的例子,例子是这样的:

In the second explanation however, I came across an example to which I have a specific question, the example is this:

解释说,对象m是分配在上的,我只是想知道这是否是完整的故事.根据我的理解,对象本身确实是在 heap 上分配的,因为new关键字已用于其实例化.

It is explained that the object m is allocated on the heap, I am just wondering if this is the full story. According to my understanding, the object itself indeed is allocated on the heap as the new keyword has been used for its instantiation.

但是,不是指向对象m的指针是同时在堆栈上分配的吗?否则,将如何访问对象本身(当然是位于中).我觉得为了完整起见,应该在本教程中提到它,而忽略它会使我有些困惑,所以我希望有人可以解决这个问题并告诉我,我对本示例的理解是正确的应该基本上有两个必须说的语句:

However, isn't it that the pointer to object m is on the same time allocated on the stack? Otherwise, how would the object itself, which of course is sitting in the heap be accessed. I feel like for the sake of completeness, this should have been mentioned in this tutorial, leaving it out causes a bit of confusion to me, so I hope someone can clear this up and tell me that I am right with my understanding that this example should have basically two statements that would have to say:

1.指向对象m的指针已在堆栈中分配

1. a pointer to object m has been allocated on the stack

2.对象m本身(因此,它携带的数据以及对其方法的访问)已分配在堆上

2. the object m itself (so the data that it carries, as well as access to its methods) has been allocated on the heap

推荐答案

您的理解可能是正确的,但陈述是错误的:

Your understanding may be correct, but the statements are wrong:

指向对象m的指针已在堆栈上分配.

A pointer to object m has been allocated on the stack.

m 指针.它在堆栈上.也许您的意思是指向Member对象的指针.

m is the pointer. It is on the stack. Perhaps you meant pointer to a Member object.

对象m本身(它所携带的数据以及对其方法的访问)已在堆上分配.

The object m itself (the data that it carries, as well as access to its methods) has been allocated on the heap.

正确的说法是m指向的对象是在堆上创建的

Correct would be to say the object pointed by m is created on the heap

通常,任何函数/方法局部对象和函数参数都是在堆栈上创建的.由于m function local 对象,因此它在堆栈上,但是m指向的对象在堆上.

In general, any function/method local object and function parameters are created on the stack. Since m is a function local object, it is on the stack, but the object pointed to by m is on the heap.

这篇关于C ++中的指针存储在堆栈或堆中的什么位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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