And if conditions work only on zero or non-zero. |
Rather, they work on
false
and
true
. It just so happens that 0 converts to
false
and non-zero converts to
true
, but this isn't fundamental.
The keyword
nullptr exists to eliminate the ambiguities caused by using the integer 0 (or the equivalent macro
NULL) in a context where a pointer is intended. Consider:
1 2 3 4
|
# include <iostream>
void f(int) { std::cout << "f(int) called\n"; }
void f(int*) { std::cout << "f(int*) called\n"; }
int main() { f(NULL); f(nullptr); }
|
f(int) called
f(int*) called |
Usually, integers are not convertible to pointers. But the integer 0 (and the equivalent macro NULL) is handled specially. The standard says that among integers, only a
prvalue 0 is considered a
null pointer constant, and only it can be converted to any pointer type.
nullptr
isn't convertible to integral types (int, long, etc.) but only to other pointers (and
bool
), and it converts to
false
or the corresponding
null pointer value, respectively.
But when we declare a local pointer instead of that variable and assign an object to it using new, the pointer won't be destroyed even if it goes out of its scope and we should use delete for it. Why is there this difference please? |
The pointer itself
will be destroyed. It's the resource that that pointer refers to which must be explicitly released by
delete
.
The pointed-to resource isn't freed automatically because
new
exists to give control over the lifetime of an object to the programmer. I saw your other question -- how else could
std::vector
store objects if the object was always destroyed only shortly after it was
new
'd?
This is a simplification, to some extent. The real answer is related to the discussion of
ownership. For the special case of pointers (really
pointer-like resources), the standard library supplies some utilities to help keep track of who is responsible for any particular resource, called smart pointers.