[英]Heap - constructor and destructor, memory allocation
我有一個帶有構造函數和析構函數的類以及另一個方法。 當我創建這個類的新實例然后它在某處調用析構函數,我不知道為什么。
class Heap
{
private:
int *heap;
int size;
int heap_size;
public:
Heap(int new_size)
{
size = new_size;
heap_size = 0;
heap = (int*)malloc(new_size*sizeof(int)); //???
//heap = new int[new_size]; //???
}
~Heap()
{
free(heap);
}
void add(int alfa)
{
// something
}
};
int _tmain(int argc, _TCHAR* argv[])
{
srand(time(NULL));
int k = rand() % 100 + 1;
Heap *name = &Heap(k);
Heap *name2 = new Heap(k); //what's the diffrence?
while (k > 0)
{
name->add(rand()); // doesn't work, because destructor is called before
k--;
}
system("pause");
return 0;
}
在運行這個非標准代碼段1的過程中 ,無論如何最有可能產生未定義的行為 2 ,這一行
Heap *name = &Heap(k);
生成一個臨時的Heap
對象,該對象在該完整表達式的末尾被銷毀。 這導致析構函數被調用。
請注意,事實仍然是你的班級非常脆弱,因為它不符合三(五)的規則 。 復制Heap
對象將導致雙重刪除。
1有充分理由,標准C ++不允許使用臨時地址。
2這種結構讓你有一個懸垂的指針。 從技術上講,取消引用name
會導致未定義的行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.