Tuesday, 12 August 2008

Using Scope for Fun and Profit

when C++ came along with it's constructors and destructors, it brought with it the idea of better understanding of scoping. We suddenly had to remember that the "int" in your for loop was only there for the duration of the looping. We realised that local variables could have destructors and could cause damage by going out of scope just as we had finished building them.

There are plenty of newbie errors to be had from the bad usage of scoping. There are however a few nice tricks that are enabled through scoping.

I wrote a profiler in an hour using scoped instances that profiled by accumulating the time between their creation and their destruction. This lead to a safe profiling system that automatically collected data without intruding in much of the code base.

Using a scoped handle is useful for ensuring that you don't hold onto something too long such as a file handle. Scoping a resource handle is very useful as it reduces the chance of leaving things dangling. The basic idea of smart pointers is that they are scoped handles to memory.

It may seem like a simple idea, but use scoping for working memory when you can too, it reduces the chance of unused and misunderstood variables.
Examples might be to have a scoped string buffer that you use for formatting stuff before using it. This can save you time and effort because you might notice a memory overrun earlier. This is because if it's scope has been reduced, then what it affects will be more immediately noticable.

No comments: