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.

3 comments:

Nathan said...

Fantastic example, I see how that was very helpful.

Allen Madsen said...

It is very useful. The only problem with the example you gave is that, if as you say, it is creating two copies of each element then going out of scope does not actually release that resource. C++ does not have a garbage collector as other languages like Java do and therefor you must manage memory yourself. Typically you would use a destructor in C++ to do this.

Zach Elko said...

The object's destructor is called automatically when the object goes out of scope. This is different from the concept of garbage collection in which the collector is aware of when no more references or handles to a resource exist, thus it can no longer be used. In the case of scope, the resource is not visible any more, thus it cannot be used. This obviously isn't the case for dynamically allocated objects because they are in scope for the duration of the program's execution after they have been declared.