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 calling main()
, but I strongly doubt any compiler does that), but also not on the heap. If, however, the line is part of a function, then indeed x
is on the stack.
Since x
is of type string*
(i.e. pointer to string), it indeed just contains the address of the string object allocated with new
. Since that string object is allocated with new
, 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:
int main()
{
std::string str("Hello"); // a string object on the stack
std::string** ptr = new std::string*(&str); // a pointer to string living on the heap, pointing to str
(**ptr) += " world"; // this adds "world" to the string on the stack
delete ptr; // get rid of the pointer on the heap
std::cout << str << std::endl; // prints "Hello world"
} // the compiler automatically destroys str here