【发布时间】:2016-02-16 05:39:32
【问题描述】:
我对 C++ 中的内存管理很陌生。我创建了一个 BigInt 类,除了影响程序性能的析构函数外,它现在已完全实现。但是,当我尝试实现析构函数时,我的程序崩溃了。
在下面的 BigInts 乘法代码中:
BigInt& BigInt::operator*=(BigInt const& other) {
//copy of this and other
BigInt* tempThis = new BigInt(*this); //1st number
BigInt* tempOther = new BigInt(other); //2nd number
//create temps so we can use value of BigInt before it is changed
BigInt* sum = new BigInt(0); //holds the eventual answer
BigInt* i = new BigInt(0);
//add *this BigInt to sum otherTemp amount of times
//this will yield multiplication answer.
for (*i; *i < *tempOther; *i = *i + 1) {
*sum += *this;
}
*this = *sum;
return *this;
}
在 for 循环中调用 *i = *i + 1 时调用析构函数,然后我认为它在我的析构函数中被删除,如下所示:
// destructor
BigInt::~BigInt() {
delete[] this->bigIntVector;
}
// copy constructor
BigInt::BigInt(BigInt const& orig)
: isPositive(orig.isPositive)
, base(orig.base)
{
this->bigIntVector = new BigIntVector(*(orig.bigIntVector));
}
一旦 'i' 被删除,就没有任何效果,整个程序就会中断。
如果有人能给我一些关于析构函数以及如何解决我的问题的指示,那将是很大的帮助。谢谢。
【问题讨论】:
-
C++ 不是 Java。该函数充满了内存泄漏。为什么你在这么多地方使用
new(而不是一次调用delete)?为什么不使用复制构造函数(你应该写的)来创建临时 BigInt 的? -
例如,这个:
BigInt* tempThis = new BigInt(*this); //1st number应该是这个:BigInt tempThis = *this;和这个:BigInt sum(0);,而不是你现在拥有的。如果这不能正常工作,那么您需要退后一步并正确实现复制构造函数(以及赋值运算符)。 -
析构函数没问题。没有什么问题。 是 错误的是您没有实现正确的复制构造函数和赋值运算符。换句话说,需要遵守“3 规则”。
-
不,它不包括它。如果你想要证明:
{ BigInteger b(10); BigInteger b2(20); b = b2;}试试,当退出{ }块时,你会看到双重删除错误和内存泄漏。
标签: c++ memory memory-management destructor bigint