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.
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.
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:
<functional>header that should be used instead, as they work fine with functions that have reference arguments. More support for currying functions than just
bind2nd(), and other functional programming goodness.
std::auto_ptr's ownership 'features', and a shared reference-counting one, that's the next best thing to garbage collection.
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.
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.):
When in doubt, don't. Operators should not be
overloaded to do something different from the normal
operator+ shouldn't do anything but
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,
See the guidelines for inline member functions. Use common sense.
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
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
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.
Last modified: Fri Oct 5 22:19:37 PDT 2001