I got an error while "if (this == nullptr)" , the error :
warning: nonnull argument 'this' compared to NULL [-Wnonnull-compare]
22 | if (this != nullptr)
The command : g++ -std=c++11 -DNDEBUG -Wall .\avl.cpp
Why can't I compare pointer with nullptr ? (null doesn't work either). How am I supposed to check if the pointer is null?
The code :
#include <iostream>
#include <stdlib.h>
namespace AVL{
template <class T>
class Node{
public:
T data;
Node<T> *left,*right;
int height;
~Node(){
delete left;
delete right;
}
Node(T& inData):data(inData),left(NULL),right(NULL),height(1){};
Node<T> * insert_node (T & inData)
{
if (this == nullptr)
return new Node<T> (inData);
if (inData < data)
left = left -> insert_node (inData);
else
right = right -> insert_node (inData);
return this;
}
private:
void compute_height(){
height=0;
if(left != NULL && left->height > height){height = left->height;}
if(right != NULL && right->height > height){height = right->height;}
}
};
}
int main ()
{
int num1=55,num2=76;
AVL::Node<int> *new_node1 = new AVL::Node<int>(num1);
AVL::Node<int> *new_node2 = new AVL::Node<int>(num2);
new_node2=new_node1->insert_node(num2);
system("pause");
}
First, it is a warning, not an error:
The compiler tries to tell you that it makes no sense to compare
this
toNULL
(or0
ornullptr
), becausethis == 0
orthis == nullptr
orthis == NULL
is nevertrue
.this
is never0
,NULL
ornullptr
. The condition can and should be removed.You can compare
this
withnullptr
or0
. It just doesn't make sense because the result is alwaysfalse
.You are not supposed to check if
this
is null, because that never happens. It's not quite clear what purpose thatif
is supposed to have in your code. If you expected it to catch errors like this:Then you were wrong. Dereferencing a null pointer is undefined behavior. You cannot call a member function on a nullpointer, hence inside a member function
this
is nevernullptr
.