What does that mean when it says 'object allocation inline on the stack'?
Especially the 'inline' bit
What does that mean when it says 'object allocation inline on the stack'?
Especially the 'inline' bit
It means that all the data for the object is allocated on the stack, and will be popped off when the current method terminates.
The alternative (which occurs in C# and Java, or if you're using a pointer in C++) is to have a reference or pointer on the stack, which refers to the object data which is allocated on the heap.
I think the "inline" here just means "as part of the stack frame for this method" as opposed to existing separately from the method.
Well, you know what the stack is, right? If you declare a function in, say, C:
int foo() {
int bar = 42;
return bar;
}
When the function is called, some space is created for information about the function on the stack, and the integer bar
is allocated there as well. When the function returns, everything in that stack frame is deallocated.
Now, in C++:
class A {
int a;
int b;
A(int x, int y) {
a = x;
b = y;
}
~A() { // destructor
cout << "A(" << a << "," << b << ") being deleted!" << endl;
}
}
void foo() {
A on_the_stack(1,2);
A *on_the_heap = new A(3,4);
}
In languages like Java, all objects are allocated on the heap (unless the compiler does some sort of optimization). But in some languages like C++, the class objects can go right on the stack just like int
s or float
s. Memory from the heap is not used unless you explicitly call new
. Note that our on_the_heap
object never gets deallocated (by calling delete
on it), so it causes a memory leak. The on_the_stack
object, on the other hand, is automatically deallocated when the function returns, and will have its destructor called prior to doing so.