Return an argument as reference is possible?

Started by
3 comments, last by alvaro 7 years, 2 months ago

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.

Advertisement

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 :)

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.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

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;
}

Stephen M. Webb
Professional Free Software Developer

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.

This topic is closed to new replies.

Advertisement