Advertisement Jump to content
Sign in to follow this  

returning a reference of vectors

This topic is 4993 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
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, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!