Thursday, May 31, 2007

Down Periscope

Hello. You've somehow stumbled upon my programming weblog. In this area, I hope to share with you various experiences I've had writing software. For this introductory post, I'll turn you on to something I was shown yesterday evening. I was so shocked/amazed/excited when I was shown this "trick" that I exclaimed aloud numerous times...

The issue I was having in my code involved objects being duplicated (copied) as I stored them in a std::vector. Oh, by the way, I code almost entirely in C++. Anyways, the way this bit of code worked was that a line was read from file, and that line was then used to construct an object of my type. From there, those objects were added to the vector. The problem was, those original objects stuck around, so I'd have TWICE as many objects in existence than I was actually using! I asked for some assistance on IRC and I must say, my life has never been the same.

The "Trick"

Maybe I've just been living under a rock, but I had never seen this before. Apparently, you can arbitrarily create scopes anywhere in your code! I'll demonstrate it below with a basic example:



Output
$ ./scope
ctor
dtor
Only 1 Foo object exists at this point, good!
dtor

Now, instead of having 2 copies of foo in existence (the one I create, and the one that gets copied into foos), I only have the one inside of foos. Depending on your situation, this is preferable because if you need to add an object to a vector, chances are good that you'll be referencing it from within the vector for the rest of the program.

Hopefully you learned something from this, stay tuned, I'll soon be posting a very amusing and interesting story about my recent job as a contract software developer. Take care.