【发布时间】:2017-10-30 19:22:24
【问题描述】:
我在 c++ 方面表现不错,但在指针和内存方面我一直很糟糕。我遇到了这种情况,不知道有没有解决办法。
typedef unsigned long long ullong;
class MathClass { //This is just an example class
public:
MathClass() {num = new ullong[1]();}
MathClass operator+(MathClass b) { //This is not my actual function, just one that has the same problem
MathClass c;
c.num[0] = num[0] + b.num[0];
delete [] num;
num = NULL;
return c;
}
public:
ullong* num;
};
这适用于这种情况。
MathClass a;
MathClass b;
for (int i = 0; i < 1000; i++) {
a = a + b;
}
因为我设置 a 等于 a + b,所以当 + 函数运行时,它会将 a 设置为等于 c 并删除旧的 a num。
对于这种情况,它会导致错误,因为我正在删除 b 的 num。
MathClass a;
MathClass b;
MathClass c;
for (int i = 0; i < 1000; i++) {
a = b + c;
}
如果我不删除 num 这会起作用,但这会导致内存泄漏。当我不删除 num 时,内存很容易超过 100MB。我敢肯定这个问题的答案很简单,但我想不通。
【问题讨论】:
-
无关:
typedef unsigned long long ullong;总是让我出于某种原因想泡茶。 -
你有什么理由使用指针和动态分配来处理像整数这样微不足道的事情?这确实增加了难度。您没有显式 Rule of Three violation 的唯一原因是您泄漏了内存。
-
总是更喜欢使用智能指针而不是原始
new/delete- 这些应该几乎从不在现代 C++ 中使用。 -
为什么要在除析构函数之外的任何地方删除?
-
在我的实际项目中,我将指针用作数组。这只是一个具有相同问题的简单类。在这个 MathClass 中,我可以只使用常规的 unsigned long long,但这不是我使用的。
标签: c++ pointers memory-leaks