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

 ̄綄美尐妖づ 提交于 2019-12-05 16:39:27

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,

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