开发者

Object allocation inline on the stack

What does that mean when it says 'object allocation inline on the stack'开发者_如何学C?

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 ints or floats. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜