Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between nullptr and nullptr_t in C++?

Tags:

c++

c++11

nullptr

Which one should I use? Any advantages if I use one over the other?

like image 770
Moiz Sajid Avatar asked Jun 24 '15 20:06

Moiz Sajid


People also ask

What is difference between nullptr and null?

Nullptr vs NULLNULL is 0 (zero) i.e. integer constant zero with C-style typecast to void* , while nullptr is prvalue of type nullptr_t , which is an integer literal that evaluates to zero.

Is it better to use null or nullptr?

Putting it All Together As a reminder, since C++11, NULL can be either an integer literal with value zero, or a prvalue of type std::nullptr_t . Because of this ambiguity, I recommend switching exclusively to nullptr . nullptr will make your code less error-prone than relying on the implementation-defined NULL .

What does nullptr stand for?

The nullptr keyword represents a null pointer value. Use a null pointer value to indicate that an object handle, interior pointer, or native pointer type does not point to an object.

What is nullptr type?

std::nullptr_t is the type of the null pointer literal, nullptr. It is a distinct type that is not itself a pointer type or a pointer to member type. Its values are null pointer constants (see NULL), and may be implicitly converted to any pointer and pointer to member type.


2 Answers

nullptr is the constant, nullptr_t is its type. Use each one in contexts where you need respectively a null pointer, or the type of a null pointer.

like image 122
Quentin Avatar answered Sep 21 '22 04:09

Quentin


"... if I use one over the other?"

You can't (use one over the other) they're orthogonal by these means:

nullptr_t is the type used to represent a nullptr

nullptr is (1)effectively a constant of type nullptr_t that represents a specific compiler implementation defined value.

See the C++11 standards section:

2.14.7 Pointer literals

  1. The pointer literal is the keyword nullptr. It is a prvalue of type std::nullptr_t.
    [ Note: std::nullptr_t is a distinct type that is neither a pointer type nor a pointer to member type; rather, a prvalue of this type is a null pointer constant and can be converted to a null pointer value or null member pointer value. See 4.10 and 4.11. — end note ]

1) Just like the this keyword nullptr stands for an rvalue rather than being of const type. Thus, decltype(nullptr) can be a non-const type. With Visual C++ 2015 and MinGW g++ 5.1 it is non-const.

like image 25
4 revs, 2 users 80% Avatar answered Sep 19 '22 04:09

4 revs, 2 users 80%