Re: Writing Efficient Arguments
On Jul 10, 5:16 pm, gpuchtel <gpuch...@gmail.com> wrote:
On Jul 10, 8:13 am, Michael DOUBEZ <michael.dou...@free.fr> wrote:
gpuchtel a =E9crit :
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;
I didn't say (or mean) 'you' would pass a temporary, I was implying
what the compiler will do (pass).
What the compiler will do is undefined. His code has undefined
behavior, so the compiler can do anything it wants. I've used
compilers that behave as he describes, but I've also used
compilers which will core dump in his initial code.
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.
That would also be fine. It's undefined behavior, and the
compiler can do whatever it wants. I'm not aware of a compiler
which does as you describe, but it wouldn't surprise me too
much.
Your example of a null pointer is not relevant to the discussion of
the (im)possibility of having a 'null' reference.
Programs with undefined behavior aren't relevent to any
discussion of how C++ behaves.:-)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34