R
ravi
Can anybody out there tell me whether it i possible to return a
reference from a function in C++
I am using Turbo C++
reference from a function in C++
I am using Turbo C++
ravi said:Can anybody out there tell me whether it i possible to return a
reference from a function in C++
I am using Turbo C++
yes, it is possible, if the object whose reference is being returned is
not local. For example:
int& increment(int& a)
{
a+1;
return a;
}
Lionel said:scratch.cpp:3: warning: reference to local variable ‘a’ returned
Why is it not an error?
Juha Nieminen said:Why is it not an error?
On Thu, 12 Jul 2007 17:09:47 +0300, Juha Nieminen wrote:
(snipped context restored)
Because the Standard says it's not. I can't think off the top of my head
a valid scenario for doing this (no doubt someone here can...),
Juha said:Why is it not an error?
Because the Standard says it's not. I can't think off the top
of my head a valid scenario for doing this (no doubt someone
here can...), but there you go... C++ is renowned for
supplying plenty of rope to hang yourself.
The reason the standard says it doesn't require a diagnostic is because
it's impossible to determine in all cases.
Ok.
The standard doesn't have too many options: if it's an error (it is),
then it is either undefined behavior,
or a diagnostic is required. And since it is impossible for a
compiler to generate the diagnostic in every case...
James said:The reason the standard says it doesn't require a diagnostic is
because it's impossible to determine in all cases. The standard
doesn't have too many options: if it's an error (it is), then it
is either undefined behavior, or a diagnostic is required. And
since it is impossible for a compiler to generate the diagnostic
in every case...
Juha said:When the compiler compiles a 'return' statement it has to know
what is being returned, naturally.
The compiler also sees all the local variables and, if necessary,
destroys them (calls destructors, etc) alongside the 'return'.
Thus it would sound trivial for the compiler to check if the
returned reference is pointing to a local variable which is destroyed
before the function is exited. It doesn't make sense to return a
reference to something which is being destroyed in the very same
statement!
When the compiler compiles a 'return' statement it has to know
what is being returned, naturally.
The compiler also sees all the local variables and, if necessary,
destroys them (calls destructors, etc) alongside the 'return'.
Thus it would sound trivial for the compiler to check if the
returned reference is pointing to a local variable which is destroyed
before the function is exited. It doesn't make sense to return a
reference to something which is being destroyed in the very same
statement!
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.