One Good thing About C++

(Note: this blog entry is more of a note to myself, rather than an info service to anybody who ends up here somehow)

Over time, after programming in a few languages, you learn about the good and bad things in each language.

C++ has many flaws, inconsistencies, or parts of the spec left up to the interpretation of the compiler writer.

It does, however, have a few cool features. One is worth mentioning.

If an object is instantiated on the stack, it is guaranteed to be destroyed when that scope goes away. It is also guaranteed that the object getting destroyed will invoke it’s destructor before leaving that scope. I think this is the coolest feature and probably the biggest win when using C++. In any other language that I know, this behaviour is not that well defined.

In C++ it is great for all sorts of things like a busy cursor or a lock object. It is the basis for the reference counting movement being put forth into the new language specs. I mean, if you have more than one exit in your function, it is too easy to miss the release of some object.

Here is a simple example:

void someFunc(void) { CWaitCursor waitCursor;

// Some stuff that will take a long time }

or..

void someFunc(void) { CFile file;

file.open(); SmartPtr spData = file.read(); // do something with data file.close(); // Some stuff that will take a long time }

Regardless of what happens in that function, even an exception…, the destructor will get called when that function leaves. For the case of the file object, you can guarantee that you don’t leak a descriptor or that the DataObj memory doesn’t get returned to the system.

Once you use it, you want to use it all the time. This feature works best with nested scopes within your code.

// Some code....

obj->release(); { CThreadLock lock; // Some very fast operation g_threadPool->remove(obj); }

delete obj;

Recently, I had to do a locking mechanism in JavaScript and it had multiple exits in the function. I had to put an un-lock at all the exits. This is very error prone.

I think this is probably similar to what some of the Aspect people like about those systems. Being able to do things regardless of how the function is entered or exited. I think more programming languages should allow hooks or triggers to occur on objects based on their scope.

This entry was posted in General. Bookmark the permalink.

Leave a Reply

Your email address will not be published.