C++ Logo

std-proposals

Advanced search

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

From: Andrey Semashev <andrey.semashev_at_[hidden]>
Date: Mon, 4 Aug 2025 14:09:19 +0300
On 4 Aug 2025 13:47, Frederick Virchanza Gotham via Std-Proposals wrote:
> 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.

And what if the argument p was nullptr in the first place?

I'm not sure what exactly you are suggesting. If pointers are supposed
to be checked before dereferencing then the above code doesn't work
because it doesn't dereference any pointers (C library functions do, but
they don't throw). If the check is performed at a different place then
you need to specify where, and why that place is adequate.

>>> 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();

No, I mean each of the methods should just return a smart pointer.

If the method must return a raw pointer, you explicitly construct a
smart pointer from it and then use the smart pointer.

> 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.

Then the API in that header needs to be wrapped so that the surrounding
code only ever uses the wrapper and smart pointers. You may argue this
is a lot of work, but that's a matter of cost/benefit balance. If you
have lots of code that depends on this low-level API with raw pointers
and you are concerned about safety then doing the work to write a
wrapper may be well justified.

Received on 2025-08-04 11:09:24