指向C ++中对象的指针-堆栈/堆中有什么? [英] Pointers to objects in C++ - what's on the stack/heap?
问题描述
我从Java开始,所以我对以下行中的堆栈/堆发生了什么感到困惑:
I started out with Java, so I am a bit confused on what's going on with the stack/heap on the following line:
string *x = new string("Hello");
其中,x
是局部变量.在C ++中,关于该语句,堆栈上是否发生任何事情?我从阅读中知道对象在堆上,但是x
呢?在Java中,x
将仅在堆栈中保存指向该对象的内存地址,但是我还没有找到一个清晰的源代码来说明C ++中发生的事情.
where x
is a local variable. In C++, does ANYTHING happen on the stack at all in regards to that statement? I know from reading it says that the object is on the heap, but what about x
? In Java, x
would be on the stack just holding the memory address that points to the object, but I haven't found a clear source that says what's happening in C++.
推荐答案
您刚刚创建的任何对象,例如您的示例中的x
在堆栈中.但是,对象x
只是一个指针,它指向分配的string
堆,您可以使用new string("Hello")
将其放置在堆上.通常,您不会在C ++中创建像这样的字符串.相反,您将使用
Any object you just created, e.g. x
in your example is on the stack. The object x
is just a pointer, though, which points to a heap allocated string
which you put on the heap using new string("Hello")
. Typically, you wouldn't create a string like this in C++, however. Instead you would use
string x("Hello");
这仍将在堆栈上分配x
.表示x
值的字符是否还驻留在堆栈上还是驻留在堆上,取决于string
实现.作为一个合理的模型,您应该假定它们在堆上(某些std::string
实现将短字符串放入堆栈对象中,避免了任何堆分配并有助于局部化).
This would still allocate x
on the stack. Whether the characters representing x
's value also live on the stack or rather on the heap, depends on the string
implementation. As a reasonable model you should assume that they are on the heap (some std::string
implementation put short string into the stack object, avoiding any heap allocations and helping with locality).
这篇关于指向C ++中对象的指针-堆栈/堆中有什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!