Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is nullptr not a special keyword and an object of std::nullptr_t? [duplicate]

Possible Duplicate:
What exactly is nullptr?

I first thought it's a keyword. My present gcc doesn't highlight nullptr in a different shade. To verify that, I wrote following:

void *&p = nullptr;

So I got some clue from the error that:

error: invalid initialization of non-const reference of type ‘void*&’ from an rvalue of type ‘std::nullptr_t’

If nullptr is an object then is it really a pointer equivalent of simple 0? In other word, suppose I write:

#define NULL nullptr

Is the above statement doesn't alter anything in my code ? Also, it would be interesting to know other use cases for std::nullptr_t type as such.

like image 489
iammilind Avatar asked Nov 28 '22 22:11

iammilind


1 Answers

It is a keyword, the standard draft says (lex.nullptr):

The pointer literal is the keyword nullptr. It is a prvalue of type std::nullptr_t.

the nullptr is not yet a pointer, but it can be converted to a pointer type. This forbids your above assignment, which is an assignment to an unrelated reference type, in which case no conversion is possible (consider int& a = 1.f;!).

Doing #define NULL nullptr shouldn't alter the behaviour unless you did use NULL in a context such as int i = 4; if(NULL == i) {}, which won't work with nullptr because nullptr is can't be treated as an integer literal.

I don't think there are many other use-cases for std::nullptr_t, it's just a sentinel because nullptr needs a type.

like image 95
Alexander Gessler Avatar answered Dec 01 '22 00:12

Alexander Gessler