C ++ 11 - Use nullptr all the time?

I'm a little bit confused.

When should I use nullptr?

I read on some sites that it should always be used, but I cannot set nullptr for a non-pointer, for example:

int myVar = nullptr; // Not a pointer ofcourse 

Should I always use NULL non-pointers and nullptr for pointers?

Thanks for the help! I am very new to C ++ 11 (and C ++ in general).

+6
source share
2 answers

Always use nullptr when initializing pointers to the value of a null pointer, that it is intended for drafts of n3485 .

[lex.nullptr] paragraph 1

The pointer literal is the nullptr keyword. This is a value of type std :: nullptr_t. [Note: std :: nullptr_t is a separate type, which is neither a pointer type nor a pointer to a member type; rather, a prvalue of this type is a null pointer constant and can be converted to a null pointer value or a null element pointer value. [...] - end note]

Now use NULL .

In accordance with the same project, it is defined as follows.

[diff.null] point 1

The macro NULL, [...] is the constant constant of a C ++ null constant pointer in this International Standard.

and a null pointer constant as follows.

[conv.ptr] paragraph 1

A null pointer constant is an integral constant expression [...] of prvalue of integer type that evaluates to 0 or prvalue of type std :: nullptr_t.

That is, this is the behavior defined by the implementation , whether NULL is defined as an integer prvalue equal to zero, or the value of the class std::nullptr_t . If this implementation of the standard library selects the first, then NULL can be assigned to whole types, and it guarantees that it will be set to zero, but if a later version is selected, the compiler is allowed to issue an error and declare the program poorly formed.

In other words, although it is conditionally valid [read IB], initializing an integer using NULL is most likely a bad idea, just use 0 instead.

On the other hand, according to the above NULL initialization of pointers to the value of a null pointer is guaranteed, as in t20>, but while NULL is a macro, which accompanies a few caveats, nullptr is a prvalue of a certain type for which type checking and conversion rules are applied. Basically, why nullptr .

+9
source

consider two overload functions:

 void foo(int) void foo(int*) 

in C ++, people tend to use 0 as a null value. Other people use NULL . ( NULL is actually just a fancy macro for 0 )

If you call foo(0) or foo(NULL) , it becomes ambiguous to be called. foo(nullptr) clears this ambiguity and will always call foo(int*) .

+2
source

Source: https://habr.com/ru/post/953734/


All Articles