Search code examples
c++returnlocal-variables

Returning a local variable in C++


I'm encountering a C++ problem (or lack there-of) because this code works, but I don't know why.

For context, my professor has given us a header file, and a main function, the program generates a Fibonnaci Sequence.

I am using an iterator to iterate the sequence using ++a and a++.

Here is my implementation of a++.

FibonacciIterator FibonacciIterator::operator++(int) //i++, increment i, return old i.
{
    FibonacciIterator old = *this; //create old object to return

    //increment actual fibonacci sequence
    long nextTemp = fCurrent + fPrevious;
    fPrevious = fCurrent;
    fCurrent = nextTemp;

    fCurrentN++;  //increment count
    return old;
}

Now, I create a value 'old', by using the dereference operator of the pointer 'this'. I do some logic to the current iterator, and return the old iterator.

This all works, and using the following do-while loop:

FibonacciIterator lIterator2 = lIterator.begin();
do
{
    cout << *lIterator2++ << endl;
} while (lIterator2 != lIterator2.end());

everything works. This do-while loop is written by the professor, we are not meant to change it.

My question is, why does this code work? To my understanding, when we create a local variable in a method, that variable is encased within the methods stack frame. When we exit the stack frame, should we return a local variable that was created in that stack frame, we might get our value. We also might not. My understanding is this is because the memory location in which this variable was created is now "up for grabs" by any program on the computer that might need it. So IF we get the value we desired, its because nothing has overwritten it yet. IF we don't, its because something has overwritten it.

So why is it that this code works, 100% of the time? Why do I not SOMETIMES see old become garbage, and crash my program with an unhandled exception? My only guess is that because 'FibonacciIterator' is a user made class, it is AUTOMATICALLY allocated memory on the heap, thus we don't run in to this problem. My only guess would be that this problem only exists using types such as int, long, double, etc.

However, I am 99% sure that my guess is wrong, and I want to understand what is going on here. I want to understand this because for one, I enjoy C++, but I don't enjoy not knowing why something works.

Thank you!


Solution

  • You can return a local object - it will be copied. You shouldn't return a pointer to a local object. As you correctly point out, the pointer will point to junk.

    In your case you've got a copy and so it is ok (with all the caveats that the copy must be "safe")