Reputation: 437
Please explain to me if "x" is a Stack-Dynamic variable or Heap-Dynamic variable in this code?And if it is Heap-Dynamic then why it is not Stack-Dynamic variable?Thank you
function foo(){ MyClass x = new MyClass();}
Upvotes: 4
Views: 15433
Reputation: 4521
Stack dynamic variables come into existence when you call a function. They exist on the C++ runtime stack, and are temporary. They are either in the parameter list, or declared inside the function (except for statics, which are not instantiated on the stack). These variables disappear when they go out of scope, and the memory for their contents is reclaimed by the runtime.
Heap dynamic instances exist in another area of memory the runtime sets aside called the "heap." These instances come into being via. the "new" operator, and must be explicitly deallocated by the "delete" operator.
I hope this is helpful
Upvotes: 8
Reputation: 4888
This specific one is: Dynamic-Heap (I'm assuming you're programming in JAVA here). As to why it's not on the stack?
See this article for general directions: http://www.maxi-pedia.com/what+is+heap+and+stack
Upvotes: 1
Reputation: 48785
I'm not sure what language this is, I'm going to go out on a limb and say it's merely pseudo code, but the concepts should be the same across most of the common OO languages.
Let's break this down:
function foo() {
MyClass x = null;
x = new MyClass();
}
The first line MyClass x = null
will allocate some space on the local stack. It's not a lot of space, just enough to store a reference.
The second line x = new MyClass()
will do a few things:
MyClass
x
reference to point to this new instance.So the simple answer is: it's both.
Upvotes: 3