on stack or heap

In the following code:

class Array {
   public:
      int& operator[] (unsigned i) { if (i > 99) error(); return data[i]; }
   private:
      int data[100];
};

int main()
{
   Array a;
   a[10] = 42;
   a[12] += a[13];
   ...
}

(Correct me if I'm wrong) The variable a of type Array is on the stack since new was not used to allocate it. The Array class has int data[100], and the operator overload returns reference to particular index in data.

Referring question.

My question is whether int data[100] is on the stack or heap ? I think it shouldn't be the stack, otherwise how can a reference return like the one above still work.

Thanks.


It's on the stack, since as you've noted a was allocated on the stack.

The stack is memory just like the heap; you can return a reference to part of it just like memory allocated on the heap. The only difference is in how the memory is managed.

The only thing you need to be careful of is not to access memory that's been deallocated; in the case of the stack, this happens at the end of a 's scope, while heap-allocated data has to be explicitly deleted.

In the question you refer to, a reference to a variable declared on the stack is returned from a function; in that case, the variable is destroyed when the function exits, which is why that code is wrong. In your case, however, you're returning a reference to part of data whose lifetime matches that of the Array object; so as long as a has not been destroyed, it's safe to access it's data in this manner.


It's on the stack. Why would the reference return be a problem? You can create and use references to things on the stack without a problem.

void foo(void)
{
 int i;
 int& j = i; // reference to variable on the stack
 j = 2;
}

What issue do you think there might be here?


It will be on the stack. If you try to use that reference after "a" has gone out of scope, you will get undefined behaviour. Hopefully it will crash soon.

链接地址: http://www.djcxy.com/p/82800.html

上一篇: 什么时候应该使用结构而不是类?

下一篇: 在堆栈或堆上