我用指針來創建一個數組,然後在析構函數Valgrind的抱怨內存泄漏,但我打電話new和delete
class cBuffer{
private:
struct entry {
uint64_t key;
uint64_t pc;
};
entry *en;
public:
cBuffer(int a, int b, int mode)
{
limit = a;
dist = b;
md = mode;
en = new entry[ limit ];
for (int i=0; i<limit; i++) {
en[i].key = 0;
en[i].pc = 0;
}
};
~cBuffer() { delete [] en; }
...
}
在另一大類我用cBuffer這樣寫道刪除過程:
class foo() {
cBuffer *buf;
foo()
{
buf = new cBuffer(gSize, oDist, Mode);
}
};
然而,Valgrind的抱怨新的運營商
==20381== 16,906,240 bytes in 32 blocks are possibly lost in loss record 11,217 of 11,221
==20381== at 0x4A0674C: operator new[](unsigned long) (vg_replace_malloc.c:305)
==20381== by 0x166D92F8: cBuffer::cBuffer(int, int, int)
您沒有遵循三個規則。 – 2013-04-28 14:37:26
見:https://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming) – 2013-04-28 14:40:43
@mahmood:見[這裏](http://stackoverflow.com/questions/4172722);如果你管理資源,並在析構函數釋放它,那麼你幾乎肯定需要落實或刪除拷貝構造函數和拷貝賦值運算符,否則,你可以用兩個對象最終都試圖釋放相同的資源。 – 2013-04-28 14:41:17