Jump to content
  • Advertisement
Sign in to follow this  
moucard

returning a reference of vectors

This topic is 4895 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

Hi again. I'd like to return a reference of a vector from a method like:
vector<CCell> &MyMethod(int index)
{
  vector<CCell> adjCells;
  // fill adjCells...
  return adjCells;
}
If I do this will adjCells be value-copied to the return variable or will the reference point to bad memory? How I'd like to use the method is:
vector<CCell> posPath = MyMethod(5);
Or do I need to declare vector<CCell> &posPath?

Share this post


Link to post
Share on other sites
Advertisement
You can't return a reference to a temporary variable because that variable is destroyed when the function exits.

You should either return a const vector<CCell> and let the compiler worying about whether it actually needs to copy it or not, or make the function return nothing and take the vector as a reference parameter.

Share this post


Link to post
Share on other sites
As you have guessed, returning a reference to a local variable is a Bad Thing™.

Returning by value may or may not be optimized away, depending on whether your compiler applies Named Return Value Optimization (NRVO) in this case or not.

Unless and until C++ gets move-constructors, the best simple solution is to just pass the reference to MyMethod.

void MyMethod(int index, vector<CCell>& adjCells);

vector<CCell> posPath;
MyMethod(5, posPath);


There are more complex methods that will allow you to use the vector<CCell> posPath = MyMethod(5); syntax - I don't know if you'll be comfortable with them. It may involve hacking your standard library (though I think he did provide a mojoized vector class...)

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!