Computer Chess Club Archives


Search

Terms

Messages

Subject: C++ programmers: the price of syntactic sugar

Author: Pat King

Date: 13:17:21 02/20/01


For what it's worth, a small tale of woe:

In accordance with Scott Meyers' "Effective C++" item 47 (don't access
uninitialized objects), I created a "guard" class to make sure that my board was
initialized as I intended.

//board.h
class  APiece{...};           //many abstract virtual functions
inline APiece* &Board(int i); //meant to be used as if declared Board[120]
inline APiece* Empty();       //returns pointer to do-nothing class

//board.cpp
struct board
{
  APiece* _B[120];
  board(){for (int i=0; i<120; i++) _B[i]=Empty();
}

inline APiece* &Board(int i)
{
  static board B; // automatically initalized on first call to Board
  return B._B[i];
}

class NoPiece:public APiece{...};

inline APiece* Empty()
{
  static NoPiece N; // single copy of nothing.
  return &N;
};

This all worked like a charm, with no worries about what order anything was
initialized, but I came to wonder (after a profiling run made it obvious that
Board() and Empty() are my two most used functions) just what price I was paying
for this minor convenience. It turns out that an access of a normal array is
some 25-30% faster than Board(), a good payoff for having to worry about
initialization.

Perhaps y'all think me naive, but perhaps this will save somebody out there a
few hassles.

Pat



This page took 0 seconds to execute

Last modified: Thu, 15 Apr 21 08:11:13 -0700

Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.