C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Standardising 0xdeadbeef for pointers

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Mon, 4 Aug 2025 11:47:00 +0100
On Sun, Aug 3, 2025 at 11:06 PM Andrey Semashev wrote:
>
> > It would allow us to write one-liner functions like:
> >
> > unsigned GetCOMportNumber(char const *const p)
> > {
> > return stoul( strstr(p, "COM") + 3 );
> > }
>
> No, it wouldn't, because C functions don't throw. Even if they did,
> existing functions would not change to start throwing.
>
> Besides, adding 3 to the result of strstr is a potential UB anyway.



You're missing the point. If the above function were to be marked as
'throw_on_nullptr', and then if the invocation of 'strstr' returns a
nullptr and has 3 added to it, it will throw an exception of type
nullptr_t, rather than segfault when 'libc' inside the implementation
of 'stoul' tries to access the memory address 0x0000000000000003.

Basically it would be as if we'd written:

 unsigned GetCOMportNumber(char const *const p)
 {
     if ( nullptr == p ) throw nullptr;
     char const *const p2 = strstr(p, "COM");
     if ( nullptr == p2 ) throw nullptr;
     return stoul( p2 + 3 );
 }

And perhaps instead of it throwing a nullptr_t, we could optionally
specify a bad return value, something like:

unsigned GetCOMportNumber(char const *const p) [[nullptr return 0]]
{
     return stoul( strstr(p, "COM") + 3 );
}

So the above function, when it encounters dodgy operations on a
nullptr, returns 0 instead of throwing nullptr.


> > and also to write a one-liner like:
> >
> > pInterface1->GetInterface2()->LastChild()->Release();
> >
> > instead of:
> >
> > if ( nullptr == pInterface1 ) return;
> > auto p = pInterface1->GetInterface2();
> > if ( nullptr == p ) return;
> > auto p2 = p->LastChild();
> > if ( nullptr == p2 ) return;
> > p2->Release();
>
> Switch your code to a smart pointer with a checked operator-> and
> operator* and there you go. Along with the associated performance penalties.


Do you mean something ilke:

  P(P(P(pInterface1)->GetInterface2())->LastChild())->Release();

Personally I find that horrible to look at. Keep in mind here that
the interfaces are defined in 3rd party header files and so we can't
go editing the header files to use checked pointers instead of raw
pointers.

Received on 2025-08-04 10:47:08