gpt4 book ai didi

C++ 复制构造函数的奇怪行为

转载 作者:太空宇宙 更新时间:2023-11-04 15:51:45 25 4
gpt4 key购买 nike

给定以下代码:

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;
}

然后在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;
}

我可以在复制构造函数的第一行设置断点,当我跨过 hash[tmpSet] = poly 行后,复制构造函数中的 p.start 为 NULL。然后,它会被第二次调用,此时 p.start 中设置了奇怪的值。

有什么线索吗?

谢谢,埃里希

编辑 1:认为将赋值运算符添加到多项式类可以修复它,但事实并非如此。仍然有同样的问题。

最佳答案

您违反了 Rule of Three :
由于您重载了复制构造函数,您应该为您的类重载复制赋值运算符析构函数

以上陈述是针对一般情况的,在您的代码示例中,您可以将应该替换为必须

关于C++ 复制构造函数的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7045416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com