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

大城市里の小女人 提交于 2019-12-07 07:55:11

问题


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.


回答1:


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.




回答2:


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)



回答3:


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.




回答4:


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 ;-)




回答5:


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


来源:https://stackoverflow.com/questions/6664115/is-nullptr-not-a-special-keyword-and-an-object-of-stdnullptr-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!