Wednesday, August 14, 2013

Coding Zen: The Knife and the Banana

There is a knife which cuts a banana. With every slice, the last piece falls into place, and the next piece always sticks to the knife.
When you finish cutting the banana, what do you do with the last piece? 
You take the last piece off as part of the destructor of your Knife Cutting. Obviously.

Keep reading to see an example at work...


Here's an embedded script. Notice on lines 24–35 of FileArray.cpp, where you have the destructor, that the destructor outs the final piece of the banana.

Our demonstration file, filearraydemo.cpp, shows that you can now use the operator[] on the left-hand side of an operator=, meaning you can actually write into a physical file as the program runs.

Let's look at our operator[] overload, lines 74–88 of FileArray.cpp. We set value to the return of getValue(index) of whatever was asked for, and then store this same information into the prevIndex and prevValue variables. Finally, we return value.

What about that if statement? Ah, there's the zen: If the operator[] is being used on the left-hand side of an operator=, this 'value' that's returned will be different, the next time the operator[] is used. If that's the case, we set the previous index to the value—and before getting or working with a new value, for the current invocation of operator[].



Finally, the destructor has that same if statement, one more time, in case the previous use of operator[] also changed value.

Just as this allows a whole banana to be cut without having to hold onto each piece you cut, this allows you to manage large arrays without eating up memory.

There you have it. The knife and the banana.

No comments:

Post a Comment