Given the following code:
class monomial {
public:
mp_real coe;
int exp;
monomial *next;
};
class polynomial
{
private:
monomial *start;
public:
polynomial();
~polynomial();
void destroy_poly(monomial *);
polynomial & operator=(const polynomial &);
polynomial(const polynomial&);
monomial * get_start();
};
polynomial::polynomial() {
start = NULL;
}
polynomial::~polynomial() {
if (start != NULL) {
destroy_poly(start);
}
start = NULL;
}
void
polynomial::destroy_poly(monomial * m) {
monomial * cm = m;
if (cm->next != NULL) {
destroy_poly(cm->next);
}
delete m;
}
polynomial::polynomial(const polynomial& p) {
if (p.start != NULL) {
start = new monomial();
start->coe = p.start->coe;
start->exp = p.start->exp;
monomial * tmpPtr = p.start;
monomial * lastPtr = start;
while (tmpPtr->next != NULL) {
monomial * newMon = new monomial();
newMon->coe = tmpPtr->next->coe;
newMon->exp = tmpPtr->next->exp;
lastPtr->next = newMon;
lastPtr = lastPtr->next;
tmpPtr = tmpPtr->next;
}
}
}
polynomial & polynomial::operator=(const polynomial &p) {
if (p.start != NULL) {
start = new monomial();
start->coe = p.start->coe;
start->exp = p.start->exp;
monomial * tmpPtr = p.start;
monomial * lastPtr = start;
while (tmpPtr->next != NULL) {
monomial * newMon = new monomial();
newMon->coe = tmpPtr->next->coe;
newMon->exp = tmpPtr->next->exp;
lastPtr->next = newMon;
lastPtr = lastPtr->next;
tmpPtr = tmpPtr->next;
}
}
return *this;
}
Then in main.cpp:
main() {
polynomial poly;
// code that initializes / sets values for
// various monomials pointed to by poly.start.
map<set<unsigned int>, polynomial> hash;
set<unsigned int> tmpSet;
tmpSet.insert(0);
hash[tmpSet] = poly;
}
I can set a breakpoint on the first line of the copy constructor, and after I step-over the hash[tmpSet] = poly line, p.start inside the copy constructor is NULL. Then, it gets called a second time, at which time p.start has strange values set inside it.
Any clue what is going on?
Thanks, Erich
EDIT 1: Thought adding the assignment operator to the polynomial class fixed it, but it did not. Still having the same problem.