Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do the advantages of using references over using pointers justify occasional "null-references"?

I'm currently designing a class hierarchy that looks roughly like this:

struct Protocol
{
    // Pass lower-layer protocol as a reference.
    Protocol(Protocol & inLLProtocol) :
        mLLProtocol(inLLProtocol)
    {
    }

    // A protocol "always" has a LLProtocol.
    Protocol & mLLProtocol; 
};


struct Layer1Protocol : Protocol
{
    // This is the "bottom" protocol, so I pass a fake reference.
    Layer1Protocol() : Protocol(*static_cast<Protocol*>(nullptr)) {}
};

IIRC binding a reference to *nullptr is safe as long as the reference is never accessed. So it is now my responsibility design my Layer1Protocol class in such a way to prevent that.

I like this approach because I ensures that all user protocols instances will have a reference to their respective lower-layer protocol (Layer1Protocol being the exception, but it is part of the core library). I think this is preferable than working with pointers because once pointers are introduced then it becomes possible to pass null-pointers, which then may need to be checked at runtime, and the result is a lot of pointer checking code and occasional bugs.

Do you think my reference-based approach is defendable? Or is using null references always a bad practice?

like image 607
StackedCrooked Avatar asked Dec 07 '25 08:12

StackedCrooked


1 Answers

IIRC binding a reference to *nullptr is safe as long as the reference is never accessed.

No, dereferencing nullptr is always undefined behaviour. You cannot have a "null reference" in a correct program.

like image 61
Cat Plus Plus Avatar answered Dec 08 '25 22:12

Cat Plus Plus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!