I use gcc8 to compile this code:
#include <iostream>
class person
{
public:
virtual void setage()=0;
};
void test(person &object)
{
if (&object == NULL) {
std::cout << "NULL object1" << std::endl;
}
if (!(&object))
{
std::cout << "NULL object1" << std::endl;
}
}
int main()
{
person *object=NULL;
person &object1=*object;
test(object1);
}
Then, two warnings come out after compiling and running:
$g++ -std=c++14 -pthread -fgnu-tm -O2 -Wall -Wextra -pedantic -pthread -pedantic-errors main.cpp -lm -latomic -lstdc++fs && ./a.out
main.cpp: In function 'void test(person&)':
main.cpp:11:17: warning: the compiler can assume that the address of 'object' will never be NULL [-Waddress]
if (&object == NULL) { ^main.cpp:15:18: warning: the compiler can assume that the address of 'object' will never be NULL [-Waddress]
if (!(&object)) ^main.cpp:15:5: warning: nonnull argument 'object' compared to NULL [-Wnonnull-compare]
if (!(&object)) ^~main.cpp:11:5: warning: nonnull argument 'object' compared to NULL [-Wnonnull-compare]
if (&object == NULL) { ^~
- Why is the address of
objectin functiontestnot NULL even passing a NULL reference value to it? - It seems that reference
objectin functiontestcan never be NULL, so we can just remove the codeif (&object == NULL){...}andif (&object == NULL) {...}to avoid these two warnings, right?
Thanks for hints.