C++ Logo

std-proposals

Advanced search

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

From: Andrey Semashev <andrey.semashev_at_[hidden]>
Date: Wed, 30 Oct 2024 13:45:27 +0300
On 10/30/24 00:56, Frederick Virchanza Gotham via Std-Proposals wrote:
> 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.

Right, so you've basically moved the checks for nullptr from the global
GetCodecName to the respective getters. Where's the benefit of your
proposal then?

Received on 2024-10-30 10:45:30