Title
Conversions to and from nullptr_t
Status
cd1
Section
7.3.12 [conv.ptr]
Submitter
Jason Merrill

Created on 2007-10-07.00:00:00 last changed 197 months ago

Messages

Date: 2008-06-15.00:00:00

[Voted into the WP at the June, 2008 meeting as paper N2656.]

Date: 2007-10-07.00:00:00

In the interest of promoting use of nullptr instead of the integer literal 0 as the null pointer constant, the proposal accepted by the Committee does not provide for converting a zero-valued integral constant to type std::nullptr_t. However, this omission reduces the utility of the feature for use in the library for smart pointers. In particular, the addition of that conversion (along with a converting constructor accepting a std::nullptr_t) would allow smart pointers to be used just like ordinary pointers in expressions like:

    if (p == 0) { }
    if (0 == p) { }
    if (p != 0) { }
    if (0 != p) { }
    p = 0;

The existing use of the “unspecified bool type” idiom supports this usage, but being able to use std::nullptr_t instead would be simpler and more elegant.

Jason Merrill: I have another reason to support the conversion as well: it seems to me very odd for nullptr_t to be more restrictive than void*. Anything we can do with an arbitrary pointer, we ought to be able to do with nullptr_t as well. Specifically, since there is a standard conversion from literal 0 to void*, and there is a standard conversion from void* to bool, nullptr_t should support the same conversions.

This changes two of the example lines in the proposal as adopted:

    if (nullptr) ;      // error, no conversion to bool
    if (nullptr == 0) ; // error

become

    if (nullptr) ;      // evaluates to false
    if( nullptr == 0 ); // evaluates to true

And later,

    char* ch3 = expr ? nullptr : nullptr; // ch3 is the null pointer value
    char* ch4 = expr ? 0 : nullptr;       // ch4 is the null pointer value
    int n3 = expr ? nullptr : nullptr;    // error, nullptr_t can't be converted to int
    int n4 = expr ? 0 : nullptr;          // error, nullptr_t can't be converted to int

I would also allow reinterpret_cast from nullptr_t to integral type, with the same semantics as a reinterpret_cast from the null pointer value to integral type.

Basically, I would like nullptr_t to act like a void* which is constrained to always be (void*)0.

History
Date User Action Args
2008-10-05 00:00:00adminsetstatus: dr -> cd1
2008-06-29 00:00:00adminsetmessages: + msg1720
2008-06-29 00:00:00adminsetstatus: drafting -> dr
2008-03-17 00:00:00adminsetstatus: open -> drafting
2007-10-07 00:00:00admincreate