Re: Null Pointer testing
On 25 Mrz., 16:55, Victor Bazarov wrote:
On 3/25/2011 11:42 AM, Juha Nieminen wrote:
Ruben Safir wrote:
Since there is implementation's and hardware where the return for a nu=
ll
pointer is not guaranteed to be zero, I take it that the syntax if(!pt=
r)
is not safe to use. So how can one test if a pointer is null?
The internal representation of a null pointer might not be all z=
ero bits,
but "ptr = 0", "ptr == 0" and "!ptr" are still guaranteed to work=
.. The
compiler performs the necessary steps under the hood to make it happen.
Now, this is an interesting question: Suppose you have:
int i;
int *intPtr =&i, *nullPtr = 0;
Will std::less<int*>()(nullPtr, intPtr) always return true in al=
l
platforms?
Since less(a,b) is specified to return a < b ([lib.comparisons]/5),
and the result of operator < for pointers when one of them is null, is
unspecified ([expr.rel/2]), then the answer is, "no, it will not". IOW,
there is no guarantee in the Standard that it would.
There is an exception for pointers. See paragraph 8:
"For templates greater, less, greater_equal, and less_equal, the
specializations for any pointer type yield a total order, even
if the built-in operators <, >, <=, >= do not."
But this exception clearly does not specify any additional behaviour
besides a total ordering. So, I would agree with Victor that even for
the less template the result is unspecified in case exactly one of the
arguments is a null pointer.
SG