Suggestions
Big Ben, London
  • Keep in mind that ++i is faster than i++ for iterators. That is, the following code:
    for (i = l.begin(); i != l.end(); ++i)
        ...
                  
    is generally faster than
    for (i = l.begin(); i != l.end(); i++)
        ...
                  
    Rationale: In `++i', operator++ returns the new value, while in `i++' it returns the old value, requiring a temporary.
  • Use assert() calls extensively to check the invariants in your code. This will dramatically decrease your debugging time by catching inconsistencies early.
  • Use the new-style C++ casts. These are cleaner and less error prone. Good Example:
    i = const_cast<int>(j);
    i = static_cast<int>(j);
    i = dynamic_cast<int>(j);
    i = reinterpret_cast<int>(j);
                  
    Bad Example:
    i = (int)j;
                  
    Rationale: "The C++ Programming Language", Third Edition.
  • Don't use `int' as the type of variables in which you store object sizes. Rationale: C and C++ define the `size_t' type as an unsigned type used for storing object sizes, and thus <object>.size() always returns `size_t'. Comparisons like the one in the following `for' loop will issue a warning about comparing signed variables (int) with unsigned ones (size_t).
    vector<int> l;
    ...
    for (int i = 0; i < l.size(); i++)
    ...
                  
    Instead, use:
    vector<int> l;
    ...
    for (size_t i = 0; i < l.size(); i++)
    ...
                  
  • Try to avoid `new' as much as possible - use local objects instead. When you have to use it, do it with auto_ptr<>()!

    Rationale: The use of STL almost eliminated the need for us to dynamically allocate memory. If we still need to do it, we have to deallocate it in both the case of normal function return and when the control exits the function through a throw. This is tedious and error prone! For objects allocated on the stack and for auto_ptr the objects will be destroyed automatically in both cases. See "The C++ Programming Language - Stroustroup" 14.4, for an excellent discussion about resource management in C++.

  • Abbreviations are evil (tm)!

    Things like 'srv' for 'server', 'chg' for 'change' and all the other abominations people use for names just make the code look ugly and confusing. Of course, well known acronyms like "HTML" are fine.

«Previous    1  2  3  4  5  6

September 3, 2005
Tudor Hulubei