c++ - Checking for this == NULL in a member-function without invoking undefined behaviour -


suppose have c++ class , have recursive member-function called instances items of class, example

// eplicit "this" clarity in following code: void recursiveprinttree(){     (if == null){ // "out" of tree         return;      }     cout << this->val;     (this->leftson)->printbinarytree();     (this->rightson)->printbinarytree(); } 

the problem of course invoking undefined behaviour calling printbinary null in first place! avoid this, , far know have @ least 3 ways of doing so:

1) using static member functions, explicit this-type argument can safely checked. did far because it's recursive implementation, of member-functions coded static. that's not good, right?

2) checking stop condition next node before having recursive call null pointer possibly "this". less natural form of writing , checks other items other this. , avoid it.

3) using default dummy values. tried it, felt it's not saving me special-case-treatment, may have been because of generic-ness of tree.

i have been fussing around matter while appreciate advice.

your code wrong.

instead of checking null in this, can check null in this->next can avoid calling method null pointers in first place.

that is, instead of:

void printbinarytree() {     if(this == null){        return;     }     cout << this->val;     this->next->printbinarytree(); } 

do this:

void printbinarytree() {     cout << this->val;     if(this->next)         this->next->printbinarytree(); } 

btw. linked list.


Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -