开发者

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

开发者 https://www.devze.com 2023-03-19 11:23 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: What exactly is nullptr?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

What exactly is nullptr?

I first thought it's a keyword. My present gcc doesn't high开发者_StackOverflow社区light 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.


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.


nullptr is a keyword that represents null pointer constant. It is of type nullptr_t, which is implicitly convertible and comparable to any pointer type or pointer-to-member type.

Read these,

  • Null pointer constant (wiki)
  • nullptr -- a null pointer literal (Bjarne Stroustrup's FAQ)


nullptr is indeed a keyword and the standard demands a type std::nullptr_t to be equivalent to typedef decltype(nullptr) nullptr_t; to enable overloading based on nullptr.


nullptr will be a keyword in next C++ standard, now called C++0x.

It is needed to disambiguate between f(int) and f(T*), so it's not simply 0, but of nullptr_t.

I didn't know gcc can highlight code ;-)


nullptr is not an object just like 0 is not an integer object. The former is a prvalue (i.e. a kind of expression) of type std::nullptr_t and the latter is an integer literal (also a kind of expression and also a prvalue) of type int.

It is possible to initialize an object with such expressions:

void* p = nullptr;
int i = 0;

It is not possible to initialize an lvalue reference with such expressions because they are prvalues; an lvalue reference can only be initialized from an lvalue.

void*& p = nullptr; // Invalid
int& i = 0; // Invalid
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号