C++ Logo

std-proposals

Advanced search

Re: [std-proposals] std::to_address(nullptr)

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Fri, 27 Jun 2025 12:55:46 +0100
On Fri, 27 Jun 2025 at 12:38, Phil Endecott <std_proposals_list_at_[hidden]>
wrote:

> Jonathan Wakely wrote:
> > On Fri, 27 Jun 2025 at 12:03, Phil Endecott via Std-Proposals <
> > std-proposals_at_[hidden]> wrote:
> >
> >> Dear Experts,
> >>
> >> Is there any reason why std::to_address() cannot be used on nullptr,
> >> returning nullptr? Should it be extended to do so?
> >
> >
> > Why?
> >
> > nullptr_t is not a pointer type and not an iterator type. The return
> value
> > is not an address, you cannot use it where a raw pointer is required
> (most
> > uses of to_address that I'm aware of involve dereferencing and/or
> > incrementing the pointer).
> >
> > What generic code do you have where you are dealing with a std::nullptr_t
> > value that you need to treat equivalently to an iterator?
>
>
> I have something that takes a pointer. Passing null is valid and
> means "don't know" or similar:
>
> void f(Foo* p);
>
> f(&something); // OK
> f(nullptr); // OK
>
> I've added an overload that takes auto and forwards to the original
> function using to_address:
>
> void f(auto p) { f(std::to_address(p); }
>
> This makes it possible to pass iterators, etc.
>
> But with this overload present, f(nullptr) fails to compile; the auto
> overload matches and tries to call to_address(nullptr).
>
> Of course it is fixable by giving the overload a suitable concept, rather
> than just auto.
>

Or adding an overload for your specific case: f(std::nullptr_t).

Either way, this seems like a problem with your code. std::to_address is
meant to be for pointer-like types, i.e. either ObjectType* or things that
have a specialization of std::pointer_traits, or provide operator->().
std::nullptr_t is none of those things. Writing a function which accepts
*anything* and then passes that to std::to_address seems like a bad design.


> Still I am curious about the situation. What would break or be
> worse if to_address() took nullptr?


It would mean I could call std::to_address and not get an address.
Currently it is guaranteed to return a raw pointer. Changing that seems
like a pretty big change (and makes the name a lie).

I would be slightly less opposed to having std::to_address(nullptr) return
a null void*, which is at least a pointer.

Received on 2025-06-27 11:56:06