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");
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++.
It's the same as in Java. The
string
orString
is on the heap, and the pointer (or reference, in Java) is on the stack.In Java, all the Objects are on the heap, and the stack is only made up of primitive types and the references themselves. (The stack has other stuff like return addresses and so on, but never mind that).
The main difference between the C++ stack and the Java stack is that, in C++, you can put the entire object directly onto the stack. e.g.
string x = string("Hello");
It's also possible, in C++, to put primitive types directly onto the heap. e.g.
int * x = new int();
. (In other words, "if autoboxing is the solution, then what was the problem?")In short, Java has rigid distinctions between primitive types and Objects, and the primitives are very much second-class. C++ is much more relaxed.
yes,
x
is on the stack : it is a local variable, which are all on the stack.The
new
operator provokes the allocation of memory on the heap.It depends on where this line is located. If it is located somewhere at file scope (i.e. outside of a function), then
x
is a global variable which definitely is not on the stack (well, in theory it could be put on the stack before callingmain()
, but I strongly doubt any compiler does that), but also not on the heap. If, however, the line is part of a function, then indeedx
is on the stack.Since
x
is of typestring*
(i.e. pointer to string), it indeed just contains the address of the string object allocated withnew
. Since that string object is allocated withnew
, it indeed lives on the heap.Note however that, unlike in Java, there's no need that built-in types live on the stack and class objects live on the heap. The following is an example of a pointer living on the heap, pointing to an object living in the stack:
Any object you just created, e.g.
x
in your example is on the stack. The objectx
is just a pointer, though, which points to a heap allocatedstring
which you put on the heap usingnew string("Hello")
. Typically, you wouldn't create a string like this in C++, however. Instead you would useThis would still allocate
x
on the stack. Whether the characters representingx
's value also live on the stack or rather on the heap, depends on thestring
implementation. As a reasonable model you should assume that they are on the heap (somestd::string
implementation put short string into the stack object, avoiding any heap allocations and helping with locality).