4.15.2005

Q&A: What's buggy about the given Instrument class below?

class Instrument {
public:
  Instrument(const char *desc);
  ~Instrument();
private:
  char *description;
};
 
Instrument::Instrument(const char *desc) {
  if (desc) {
    description = new char[strlen(desc) + 1];
    strcpy(description, desc);
  }
  else {
    description = new char[1];
    *description = '\0';
  }
}

inline Instrument::~Instrument() { delete [] description; }

Default assignment operator doesn't work for dynamically allocated memory.

 Instrument a("a 14.00%, 17.50 year bond bought at $950.00");
 Instrument b("a 14.00%, 18 year bond bought at $1000.00");
 b = a;

  • the memory that b used to point to was never deleted
  • both a and b now contain pointers to the same character string. When one of them goes out of scope, its destructor will delete the memory still pointed to by the other.

Category: C++ Quant > C++

No comments:

Post a Comment