C++ Logo

std-proposals

Advanced search

[std-proposals] null reference

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Wed, 3 Apr 2024 23:57:13 +0100
Back in 1993, they were talking about null references:

    http://www.virjacode.com/cxxproposals/compstdcxx/article86414

If we were to have null references now 31 years later, here's how I'd do them:

    int &myref = *nullptr;

Normally it's undefined behaviour to dereference a nullptr, but if you
dereference the compile-time constant expression 'nullptr', you get
the null reference. And so then if you write a function that takes a
reference, you can check if it's a null reference as follows:

    void Func(int &arg)
    {
        if ( arg == *nullptr ) return;
    }

You can use a static_cast to get a null reference of a specific type:

    static_cast<MyClass&>( *nullptr );

As Pascual said back in 1993, this would be useful for a method that
returns an element from a container:

     Y& X::operator[](size_t index){...}

If your index is out of range, the method returns a null reference.

Received on 2024-04-03 22:57:26