• 9
• 11
• 9
• 20
• 12

# Return an argument as reference is possible?

This topic is 429 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I want to return an argument as a reference. Something like:

Foo& GetFoo(Foo f)
{
...
return f;
}


I know returning a local variable as a reference doesn't works:

Foo& GetFoo()
{
Foo f;
...
return f;
} // f is destroyed here


Also i know that returning a global variable as a reference works:

Foo f;
...
Foo& GetFoo()
{
...
return f;
}


But i don't know about arguments, and i didn't see anything about.

##### Share on other sites

An argument as in your first example:

Foo& GetFoo(Foo f)

is just the same as a temporary, at function scope. So if you try to return that by reference, it won't work.

What are you trying to do exactly? As is, it sounds like a code-smell. Try to explain what your actual problem is, and we can give you some possible solutions :)

##### Share on other sites
If the argument is a value-type, it has the same restriction as a local variable - i.e. you can't return a reference to it.

If the argument is already a reference, you can return that reference back out safely, but it's kind of a weird thing to do.

##### Share on other sites

If the argument is a value-type, it has the same restriction as a local variable - i.e. you can't return a reference to it.

If the argument is already a reference, you can return that reference back out safely, but it's kind of a weird thing to do.

Nonsense.  It's a very common thing to do.  It's all though the standard library.

std::ostream&
operator<<(std::ostream& ostr, std::string const& s)
{
s.streambuf.copyin(s);
return ostr;
}


##### Share on other sites
No. An argument behaves similarly to a local variable. In particular, it lives on the stack, and its scope ends with the function. Returning a pointer or a reference to it won't work.

EDIT: Some stupid add made me think there were no responses to the original question. Sorry, I didn't add anything of value. Edited by Álvaro