Returning a “NULL reference” in C++?

前端 未结 8 586
旧巷少年郎
旧巷少年郎 2020-12-05 00:02

In dynamically typed languages like JavaScript or PHP, I often do functions such as:

function getSomething(name) {
    if (content_[name]) return content_[na         


        
8条回答
  •  感动是毒
    2020-12-05 00:15

    This code below demonstrates how to return "invalid" references; it is just a different way of using pointers (the conventional method).

    Not recommended that you use this in code that will be used by others, since the expectation is that functions that return references always return valid references.

    #include 
    #include 
    
    #define Nothing(Type) *(Type*)nullptr
    //#define Nothing(Type) *(Type*)0
    
    struct A { int i; };
    struct B
    {
        A a[5];
        B() { for (int i=0;i<5;i++) a[i].i=i+1; }
        A& GetA(int n)
        {
            if ((n>=0)&&(n<5)) return a[n];
            else return Nothing(A);
        }
    };
    
    int main()
    {
        B b;
        for (int i=3;i<7;i++)
        {
            A &ra=b.GetA(i);
            if (!&ra) std::cout << i << ": ra=nothing\n";
            else std::cout << i << ": ra=" << ra.i << "\n";
        }
        return 0;
    }
    

    The macro Nothing(Type) returns a value, in this case that represented by nullptr - you can as well use 0, to which the reference's address is set. This address can now be checked as-if you have been using pointers.

提交回复
热议问题