C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Calling methods on a nullptr

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Tue, 29 Oct 2024 21:56:56 +0000
On Tue, Oct 29, 2024 at 8:48 PM Andrey Semashev wrote:
>
>
> > You could replace it with:
> >
> > string GetCodecName(Manager *const pmanager)
> > {
> > return pmanager->GetDevice()->GetChannel(0)->GetLowPassFilter()->GetCodecName();
> > }
> >
> > That's the kind of lines I was thinking along.
>
> The two pieces of code are not equivalent, even assuming the proposal is
> accepted. Specifically, the second piece is missing `return {}`, and in
> fact it's not clear what this code is supposed to do if any if the
> pointers are null. Even if you did define some sort of behavior in this
> case, I wouldn't describe this code as something that is easy to understand.


Here's how each of those methods could be defined:

    Device *Manager::GetDevice(void) { if ( nullptr == this ) return
{}; return this->pdev; }
    Channel *Device::GetChannel(void) { if ( nullptr == this ) return
{}; return this->pchannel; }
    Filter *Channel::GetLowPassFilter(void) { if ( nullptr == this )
return {}; return this->plow; }
    string Filter::GetCodecName(void) { if ( nullptr == this ) return
{}; return this->codec_name; }

What this means is that you can chain them without checking for a
nullptr at each step, something like:

    pmanager->GetDevice()->GetChannel(0)->GetLowPassFilter()->GetCodecName();

I'm not sure if this is a fantastic idea but I think it's worth looking at.

Received on 2024-10-29 21:57:09