Re: Writing Efficient Arguments
gpuchtel wrote:
On Jul 10, 8:13 am, Michael DOUBEZ <michael.dou...@free.fr> wrote:
gpuchtel a ?crit :
On Jul 10, 6:41 am, Michael DOUBEZ <michael.dou...@free.fr> wrote:
AFAIK the following code is valid (though UB):
void print(int& i)
{
cout<<&i<<endl;
}
int main()
{
print(*static_cast<int*>(0));
return 0;
}
And prints '0'.
A reference cannot be 'null'. What you did created a tempory int
variable that was initialized to 0 (zero), then a reference to that
temporary variable was passed to the print function, which in turn
printed '0'.
Where did you get that from ? Even if I wanted it, I couldn't pass a
temporary because the ref is not const.
It is perhaps more understandable if you replace by:
int *ptr=NULL;
print(*ptr)
and add in print
++i; //cause segfault;
Michael- Hide quoted text -
- Show quoted text -
I didn't say (or mean) 'you' would pass a temporary, I was implying
what the compiler will do (pass). Simply stated, there is no such
thing as a 'null' reference. All your example does is to create a
reference to a (tempory) int value that contains the value of zero.
No temporary of type 'int' exists (or created) in the expression
static_cast<int*>(0)
The compiler should see the _integer_literal_ 0 and the static_cast
to a pointer type, and should create a *null pointer value* (of type
'int*', a pointer to int). It's all done in compile time.
Your example of a null pointer is not relevant to the discussion of
the (im)possibility of having a 'null' reference.
Why isn't it? As shown, the example is essentially the same as
...
int *p = 0;
print(*p); // no static cast needed
...
IIRC, most recent proposed corrections to the Standard actually allow
creation of a "null reference" provided that the contents of the
referred object are never evaluated (no lvalue-to-rvalue conversion
is performed). Taking address of that reference (using the operator
& on it) should yield a null pointer.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask