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
awas 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
datawhose lifetime matches that of theArrayobject; so as long asahas not been destroyed, it’s safe to access it’s data in this manner.