C++ Commandments

I don't like C++ much. But when I use it, here are some things I try to keep in mind to make my life much easier that are probably worth sharing.. In addition to these, pretty much everything in Scott Meyers' Effective C++ series of books holds true.

Libraries

The Standard C++ Library

Especially the STL. Learn it. Love (almost) all of it. Have sex with it. Volunteer to sleep in the wet spot afterwards. It's that good. Especially the STL. Avoid reinventing the wheel when the library has something for it. The few exceptions are mentioned below.

Personally, I like the STLPort implementation. If you have a C++ compiler, STLPort probably works with it, and, unlike many packaged-with-compiler C++ libraries, is actually fully standard-compliant, with minimal extenstions, in the form of a few extra container types.

Boost

The Boost library is a large collection of mostly quite useful stuff, written by some of the best C++ people around, including many who were on the C++ standardization committe. Among the niftier things:

Classes

Destructors

Always have destructor functions, even if they're empty to start out with. As your code evolves, you might end up needing one, and it's a lot easier if there's already one ready for you to add to.

Inline class methods

My rules of thumb for these (Member functions defined in the class definition, not just declared and prototyped. The inline keyword is another, similar story.):

Overloading operators

When in doubt, don't. Operators should not be overloaded to do something different from the normal meaning. operator+ shouldn't do anything but addition. operator<< and operator>> shouldn't do anything but shifting bits (The standard iostreams stuff is very guilty of breaking this rule. It sucks. No nookie for it!). About the only operators that should be overloaded on a regular basis are operator= (Assignment), the comparision operators when it makes sense to be able to compare objects, and, for functors, operator().

Functions

Inline functions

See the guidelines for inline member functions. Use common sense.

Non-const reference arguments

Use these with caution. A non-const reference could be modified, which might bite you if you're not prepared for that. If a function is going to modify its arguments, I prefer to make this crystal-clear via explicit pointers rather than the syntactic sugar of references. The exception is for classes like std::vector, where passing references can be thought of much like arrays decaying into pointers which can be used to modify its contents. On the flip side, prefer const references to const pointers, to avoid having to check for null pointers.

Functors (Classes that have an operator())

They're not the same thing as first-class functions, but they're the closest you can get in C++. Mmm, lisp-y. They play well with the STL and Boost's functional bits too.


Shawn Wagner

Last modified: Fri Oct 5 22:19:37 PDT 2001

Valid XHTML 1.0! Valid
CSS!