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++.
Any object you just created, e.g.
xin your example is on the stack. The objectxis just a pointer, though, which points to a heap allocatedstringwhich 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
xon the stack. Whether the characters representingx‘s value also live on the stack or rather on the heap, depends on thestringimplementation. As a reasonable model you should assume that they are on the heap (somestd::stringimplementation put short string into the stack object, avoiding any heap allocations and helping with locality).