vendredi 27 février 2015

memory management for linked list and tree programs in c++

I solve algoritm questions from sites like leetcode, hacker rank or cracking the coding interview. I do most if the questions in c++. So for most of them i have a node struct as below



struct Node {
Node* next;
//for tree
Node* left;
Node* right;
int data;
//ctor
Node(int val) : left(nullptr);.....
};


then i have a function(s) which implements the algorithm



bool someAlgorithm(Node* root) {
//do stuff
}


and finally i create the nodes in the main



int main() {
auto root = new Node(4);
root->left = new ..
root->left->left = new ..
}


I want to incorporate memory management in this kind of solutions. If i use c++11 shared_ptr do i need to provide a destructor ? if yes what should i write in the destructor ? But i found that shared_ptr makes code overly complex and un-understandbale for such small programs.


In general what is the best way to make solving such questions memory safe ?


Aucun commentaire:

Enregistrer un commentaire