C++ Logo

std-proposals

Advanced search

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

From: Andrey Semashev <andrey.semashev_at_[hidden]>
Date: Tue, 29 Oct 2024 23:48:03 +0300
On 10/29/24 23:20, Frederick Virchanza Gotham via Std-Proposals wrote:
> On Tue, Oct 29, 2024 at 5:01 PM Jeremy Rifkin via Std-Proposals wrote:
>>
>> Do you have a concrete example of a problem that could be uniquely
>> solved by being able to call a member function on a null pointer? My
>> gut feeling is that this is an anti-pattern and symptom of bad design
>> however, I might not be considering all possible use cases.
>
>
> Well what came to mind for me first was where you have code like the following:
>
> string GetCodecName(Manager *const pmanager)
> {
> if ( nullptr == pmanager ) return {};
> auto *const pdev = pmanager->GetDevice();
> if ( nullptr == pdev ) return {};
> auto *const pchannel = pdev->GetChannel(0);
> if ( nullptr == pchannel ) return {};
> auto *const plow = pchannel->GetLowPassFilter();
> if ( nullptr == plow ) return {};
> return plow->GetCodecName();
> }
>
> 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.

Received on 2024-10-29 20:48:07