Что именно является nullptr?

Используйте этот параметр

 bool c = a.Equals(b);
539
задан Josh Lee 9 October 2013 в 12:36
поделиться

5 ответов

How is it a keyword and an instance of a type?

This isn't surprising. Both true and false are keywords and as literals they have a type ( bool ). nullptr is a pointer literal of type std::nullptr_t, and it's a prvalue (you cannot take the address of it using &).

  • 4.10 about pointer conversion says that a prvalue of type std::nullptr_t is a null pointer constant, and that an integral null pointer constant can be converted to std::nullptr_t. The opposite direction is not allowed. This allows overloading a function for both pointers and integers, and passing nullptr to select the pointer version. Passing NULL or 0 would confusingly select the int version.

  • A cast of nullptr_t to an integral type needs a reinterpret_cast, and has the same semantics as a cast of (void*)0 to an integral type (mapping implementation defined). A reinterpret_cast cannot convert nullptr_t to any pointer type. Rely on the implicit conversion if possible or use static_cast.

  • The Standard requires that sizeof(nullptr_t) be sizeof(void*).

384
ответ дан 22 November 2019 в 22:20
поделиться

Well, other languages have reserved words that are instances of types. Python, for instance:

>>> None = 5
  File "<stdin>", line 1
SyntaxError: assignment to None
>>> type(None)
<type 'NoneType'>

This is actually a fairly close comparison because None is typically used for something that hasn't been intialized, but at the same time comparisons such as None == 0 are false.

On the other hand, in plain C, NULL == 0 would return true IIRC because NULL is just a macro returning 0, which is always an invalid address (AFAIK).

5
ответ дан 22 November 2019 в 22:20
поделиться

Если у вас есть функция, которая может получать указатели на другие чем один тип, вызов его с помощью NULL неоднозначен. То, как это работает сейчас, очень хакерское, принимая int и предполагая, что оно NULL .

template <class T>
class ptr {
    T* p_;
    public:
        ptr(T* p) : p_(p) {}

        template <class U>
        ptr(U* u) : p_(dynamic_cast<T*>(u)) { }

        // Without this ptr<T> p(NULL) would be ambiguous
        ptr(int null) : p_(NULL)  { assert(null == NULL); }
};

В C ++ 11 вы можете перегрузить nullptr_t , так что ptr p (42); будет ошибкой времени компиляции, а не выполнением assert .

ptr(std::nullptr_t) : p_(nullptr)  {  }
36
ответ дан 22 November 2019 в 22:20
поделиться

Это ключевое слово, потому что стандарт определяет его как таковое. ;-) Согласно последнему общедоступному проекту (n2914)

2.14.7 Литералы указателя [lex.nullptr]

 литерал-указатель:
nullptr

Литерал указателя - это ключевое слово nullptr . Это r-значение типа std :: nullptr_t .

Это полезно, потому что оно не выполняет неявное преобразование в целое значение.

3
ответ дан 22 November 2019 в 22:20
поделиться

From nullptr: A Type-safe and Clear-Cut Null Pointer:

The new C++09 nullptr keyword designates an rvalue constant that serves as a universal null pointer literal, replacing the buggy and weakly-typed literal 0 and the infamous NULL macro. nullptr thus puts an end to more than 30 years of embarrassment, ambiguity, and bugs. The following sections present the nullptr facility and show how it can remedy the ailments of NULL and 0.

Other references:

57
ответ дан 22 November 2019 в 22:20
поделиться
Другие вопросы по тегам:

Похожие вопросы: