A reference can not be NULL or it can be NULL?

后端 未结 7 931
忘了有多久
忘了有多久 2020-12-13 16:03

I have read from the Wikipedia that:

“References cannot be null, whereas pointers can; every reference refers to some object, although it may or may n

7条回答
  •  失恋的感觉
    2020-12-13 16:49

    gcc8 will give a warning about it:

    warning: the compiler can assume that the address of 'object1' will never be NULL [-Waddress]

    A small demo:

    #include 
    
    class person
    {
        public:
            virtual void setage()=0;
    };
    
    int main()
    {
        person *object=NULL;
        person &object1=*object;
    
        if (&object1 == NULL) {
            std::cout << "NULL object1" << std::endl;
        }
    
        if (!(&object1)) {
            std::cout << "NULL object1 " << std::endl;
        }
    }
    

    Compile and running output:

    g++ -std=c++2a -pthread -fgnu-tm -O2 -Wall -Wextra -pedantic -pthread -pedantic-errors main.cpp -lm -latomic -lstdc++fs && ./a.out

    main.cpp: In function 'int main()':

    main.cpp:14:18: warning: the compiler can assume that the address of 'object1' will never be NULL [-Waddress]

     if (&object1 == NULL) {
    
                  ^
    

    main.cpp:18:19: warning: the compiler can assume that the address of 'object1' will never be NULL [-Waddress]

     if (!(&object1)) {
    
                   ^
    

    NULL object1

    NULL object1

提交回复
热议问题