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

后端 未结 7 929
忘了有多久
忘了有多久 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:30

    that would crash your program. Did you try running it? doing *object will deference a null pointer, so in fact your reference never gets assigned.

    0 讨论(0)
  • 2020-12-13 16:32

    Well, you can do whatever you want in C++. Another example:

    person &object1 = *( reinterpret_cast<person*>(0) );
    

    You are invoking an undefined behavior in the above case, beside the case you mentioned!

    0 讨论(0)
  • 2020-12-13 16:33

    Saying person &object1=*object is not the same thing as saying person &object1=NULL. Probably the compiler is just not smart enough to find out that you are dereferencing null pointer, but you'll get a runtime error anyway. So they are kind of true still ;)

    0 讨论(0)
  • 2020-12-13 16:41

    In your code:

    person *object=NULL;
    person &object1=*object;
    

    you dereference a NULL pointer, so you get undefined behaviour. And to answer your question, there is no such thing as a NULL reference.

    And to address the other part of your question, just because a program compiles, there is no guarantee that it is correct or that it will work. C++ compilers are not required to even attempt to diagnose the kind of error your code contains.

    0 讨论(0)
  • 2020-12-13 16:42

    You can have a null reference, not sure why anyone would say otherwise, it is a nasty side effect of some operations. You just can't create one directly.

    0 讨论(0)
  • 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 <iostream>
    
    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

    0 讨论(0)
提交回复
热议问题