Friday, March 9, 2012

Getting my hands dirty with C++

Today I am working on a project in C++ for a computer graphics class.

C++ is interesting for a number of reasons; I generally appreciate it for the same reason the Newfie enjoyed banging his head on the wall...because it feels so good when I stop.

I jest. On a more serious note, I will take a moment to note a plus or two (pun++!) about C++. I find C++ interesting because of the expressive power it has compared to e.g. Java. One of the design decisions of OO in Java is that all object instances reside on the heap. That is because in Java, the garbage collector is responsible for freeing resources. That is cool when that is how you expect the System to operate, but there may be times when you want resources to be freed when their intended use has passed out of lexical scope; in other words, when some body of code has finished executing.

C++ of course allows the programmer to allocate object instances within stack frames. The answer is to declare them like any other variable, e.g.:

Foo aFoo(aParam);

This looks similar to "Foo aFoo = new aFoo(aParam)" in Java. However, because "new" isn't used, in C++ this is a stack variable allocation, and not a heap allocation. The "delete" keyword isn't required as the destructor will be called automatically when aFoo passes out of scope. Besides the fact that the deallocation of the object instance will possibly be deferred for a while in Java, the two stories look more or less the same.

However, when exceptions enter the picture, things are a little different. C++ is gracious enough to unwind the stack for you, and that means that for each block (a lexical scope) on the stack, object instances allocated within those blocks will be deallocated. In Java, this is not possible.

This leads to an important idiom in C++, invented by the venerable Bjarne Stroustrup himself, Resource Acquisition Is Instantiation. If resources must be freed, those resources may be acquired in the constructor of a class and freed in the destructor. Then an object of such a class can be instantiated inside a method or function body as a local variable. Whether an exception is thrown or not, because the destructor will be called, the resource will be freed.

There are ways to approximate this in Java and in other languages, e.g. a "with" block in Python will do more or less the same thing.

So where does that leave us? I'll try and close with an interesting thought. As a beginning programmer, I was intrigued by syntax. I think the most important parsers on the planet are human, so I still think syntax is important. But behind the syntax is meaning, is semantic. Javascript and Scheme have wildly differing syntaxes for meaning the same things. Here we saw an example of a humble line of Algol-derived syntax meaning completely different things in two closely-related languages.

No comments:

Post a Comment