Home > Backend Development > C++ > Why is `nullptr` a Better Choice than `NULL` and `0` for Pointers in C ?

Why is `nullptr` a Better Choice than `NULL` and `0` for Pointers in C ?

Linda Hamilton
Release: 2024-11-08 12:55:02
Original
283 people have browsed it

Why is `nullptr` a Better Choice than `NULL` and `0` for Pointers in C  ?

Using nullptr: Advantages over NULL and 0

Pointers must be properly initialized to avoid unexpected behavior. While the syntax int* p1 = nullptr;, int* p2 = NULL;, and int* p3 = 0; may seem functionally equivalent, there are significant advantages to using nullptr over the other two options.

Overloading Ambiguity Resolution:

Consider the overloaded functions:

void f(char const *ptr);
void f(int v);

f(NULL);  // ambiguous function call
Copy after login

With NULL, the compiler cannot determine which function to call, as it could be either f(char const *) or f(int). This ambiguity can lead to unexpected errors. However, using nullptr resolves this ambiguity:

f(nullptr); // calls f(char const *)
Copy after login

Template Specialization:

In C , the type of nullptr is nullptr_t. This allows for template specialization for nullptr, providing unparalleled flexibility:

template<typename T, T *ptr>
struct something{};                     // primary template

template<>
struct something<nullptr_t, nullptr>{};  // partial specialization for nullptr
Copy after login

Using this specialization, you can handle nullptr arguments uniquely:

template<typename T>
void f(T *ptr);   // function to handle non-nullptr argument

void f(nullptr_t); // overload to handle nullptr argument
Copy after login

The above is the detailed content of Why is `nullptr` a Better Choice than `NULL` and `0` for Pointers in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template