Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is nullptr rvalue

While looking at the implementation of nullptr here, what got my attention is that nullptr is rvalue which means we can do something like this

std::nullptr_t&& nullref = nullptr;

But how could nullptr be rvalue since the implementations is something like this

const class {...} nullptr = {};

Is this core feature ? What am I missing ?

like image 312
Laith Avatar asked Jul 10 '16 22:07

Laith


2 Answers

Implementation has nothing to do with it.

The keyword nullptr is defined to produce an rvalue expression, and that's the end of it.

[C++14: 2.14.7/1]: The pointer literal is the keyword nullptr. It is a prvalue of type std::nullptr_t. [ Note: std::nullptr_t is a distinct type that is neither a pointer type nor a pointer to member type; rather, a prvalue of this type is a null pointer constant and can be converted to a null pointer value or null member pointer value. See 4.10 and 4.11. —end note ]

I agree you couldn't yourself reimplement it to this criterion in userspace, but then that's the case for every single other keyword also.

Expressions consisting only of the keywords true and false are also rvalues, if you're curious.

[C++14: 2.14.6/1]: The Boolean literals are the keywords false and true. Such literals are prvalues and have type bool.

like image 195
Lightness Races in Orbit Avatar answered Sep 19 '22 10:09

Lightness Races in Orbit


If Alternative #1 were the definition of nullptr, then you are right that it would be an lvalue. However, it could be forced to be an rvalue using something like this:

const class __nullptr_t {...} __nullptr = {};
#define nullptr (__nullptr_t(__nullptr));

That's not what was ultimately standardized though. In actual C++11, nullptr is a literal, the same way as 3.14 or 'x'.

like image 21
Brian Bi Avatar answered Sep 21 '22 10:09

Brian Bi