Jump to content
  • Advertisement
Sign in to follow this  
JustAnotherCppProgrammer

Return an argument as reference is possible?

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
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 :)

Share this post


Link to post
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 this post


Link to post
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 this post


Link to post
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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!