The Wabe Personal Notebook C++ Coding Strategies


C++ Coding Strategies

Never wait for execution time!

The C++ compiler offers many ways to catch errors during the compilation phase. Keep that in mind when developing a design.

Use templates and overloading instead of void pointers and variable arguments

This means taking advantage of overloading and templates. Type-safe functions save time and effort, and often result in a faster program (at the expense of code size, of course). If code space is a problem, consider using a template as a front-end to a void pointer-based class or function.

Having a template-based class inherit from an abstract class allows one to do type tagging automatically. Explicit type tagging can often result in errors when the implementation is changed without changing the interface.

Don't be afraid of redefining the memory manager

Remember, the default memory manager might be inefficient, but it does work well. If you are going to create and destroy a lot of small-to-medium sized objects, you might consider allocating space in bulk and providing your own memory management system.

Remember also, if you do redefine the manager, you'll need to provide both new() and delete() static methods. One approach is to make a general purpose MM class and take advantage of the optional argument to new() and delete().

Example:

class MemoryManagement {
public:
  virtual allocate( ... );
  virtual free( ... );
};
  
class PersistantStorage : public MemoryManagement {
public:
  allocate( ... );
  free( ... );
};

class myClass {
public:
  void* operator new ( size_t, MemoryManagement& );
  void  operator delete ( void* );
};
  
PersistantStorage storage( "./stor.mm" );

myClass* x = new(storage) myClass;
       

Avoid dispatching unless you know what you're doing

This means if you are providing member functions that map directly to member functions of a field object, you're duplicating interfaces. Instead, provide one access member function to the object in question.

Example:

class A {
  B& b;

public:
  int get_x( void ) const { return b.get_x(); }
  int get_y( void ) const { return b.get_y(); }
};
       

should be:

class A {
  B& b;

public:
  const B& get_b( void ) const { return b; }
};

object_A.get_b().get_x();
       

Unless the compiler is really cheesy, this is no less efficient than the previous example. Call-chains like the one above can actually be self-documenting if the member function names are chosen carefully.

Last Modified: 2005/03/27 04:38:54 GMT
(Send problems to Rob Menke)
Page style: Classic | Cyan | Dark