return reference or not

V

Viet Le Hong

Should I return reference to a temporaty object in a function. I think I
should but g++ 3.2 always warns this thing.

Eg
..
A& test(A &a, A &aa)
{
A res;
.........
.... doing some thing....

return res;
}


Viet
 
J

Jakob Bieling

Viet Le Hong said:
Should I return reference to a temporaty object in a function. I think I
should but g++ 3.2 always warns this thing.

Why do you think you should?
Eg
.
A& test(A &a, A &aa)
{
A res;
.........
.... doing some thing....

return res;

Here the object 'res' will be destroyed, so the reference is invalid.
That is why it is not allowed. And yes, g++ 3.2 is right.

hth
 
W

WW

Jakob said:
Why do you think you should?


Here the object 'res' will be destroyed, so the reference is
invalid. That is why it is not allowed. And yes, g++ 3.2 is right.

Calrification: Actually it is allowed, "only" results in undefined behavior.
g++ is very nice and warns about things like this but not all:

char const *getC() {
std::string x;
// add something to x
return x.c_str();
}

Same thing in another form, but g++ has already no way to detect this.
 
N

Niklas Borson

jeffc said:
What makes you think you "should"?

Should a reference outlive the object it refers to?

The answer to your question is the same as the answer to the
above question.
 

Ask a Question

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.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,142
Messages
2,570,819
Members
47,367
Latest member
mahdiharooniir

Latest Threads

Top