开发者

how to Clean up(destructor) a dynamic Array of pointers?

开发者 https://www.devze.com 2022-12-30 23:09 出处:网络
Is that Destructor is enough or do I have to iterate to delete the new nodes?? #include \"stdafx.h\" #include<iostream>

Is that Destructor is enough or do I have to iterate to delete the new nodes??

#include "stdafx.h"  
#include<iostream>  
using namespace std;  
struct node{  
    int row;  
    int col;  
    int value;  
    node* next_in_row;  
    node* next_in_col;  
};  

class MultiLinkedListSparseArray {  
private:  
    char *logfile;  
    node** rowPtr;  
    node** colPtr; // used in constructor  
    node* find_node(node* out);  
    node* ins_node(node* ins,int col);  
    node* in_node(node* ins,node* z);  
    node* get(node* in,int row,int col);  
    bool exist(node* so,int row,int col);  
    //add anything you need
public:  
    MultiLinkedListSparseArray(int rows, int cols);  
    ~MultiLinkedListSparseArray();  
    void setCell(int row, int col, int value);  
    int getCell(int row, int col);  
    void display();  
    void log(char *s);  
    void dump();  
};  

MultiLinkedListSparseArray::MultiLinkedListSparseArray(int rows,int cols){  
    rowPtr=new node* [rows+1];  
    colPtr=new node* [cols+1];  
    for(int n=0;n<=rows;n++)  
        rowPtr[n]=NULL;  
    for(int i=0;i<=cols;i++)  
        colPtr[i]=开发者_如何学GoNULL;  
}  

MultiLinkedListSparseArray::~MultiLinkedListSparseArray(){ // is that destructor enough??  
    cout<<"array is deleted"<<endl;  
    delete [] rowPtr;  
    delete [] colPtr;  
}  


If you inserted object pointers on those arrays(initially you are initializing them to NULL), you need to iterate them to delete each single object.

As always, one delete for each new.


The golden rule is that you have to call delete once for every time you called new. If you only call new once to construct the array you only need to call delete once to destroy it.

If you call new on an item before adding it to the list and forget about the item you have to call delete on those as well in the destructor.

Above you are initializing an array of pointers, and the 4 bytes per pointer only will be freed correctly.

I usually track the responsibility of each item in my code, if you add an item to the list, does the list take over responsibility for the object? If you have something like new the item, add it to the list and destroy the pointer to the new object, leaving only the list with a reference to it, then the list has to take over responsibility for cleaning the memory and it would have to iterate the items and free them one by one.


Use an off-the-shelf container for arrays that handle pointers. There is rarely a need to roll your own, and if perchance there is then generalize it so that it can be reused.

0

精彩评论

暂无评论...
验证码 换一张
取 消