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 20:20:08 +0000
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.

Received on 2024-10-29 20:20:21