Jessica
Jessica

Reputation: 2435

How do I return an object in C++ without it going out of scope?

I am writing code to find the sum of two vectors:

// Vector operations
TIntV& FindSum(const TIntV& v1, const TIntV& v2) {
  AssertR(v1.Len() == v2.Len(), TStr::Fmt("Vector lengths unequal"));
  TIntV vSum = TIntV(v1);
  for (int i = 0; i < vSum.Len(); i++) {
    vSum[i] += v2[i];
  }
  return vSum;
}

I need to return the sum, but I am getting back the zero vector, because vSum seems to be going out of scope.

utilities.cpp:6: warning: reference to local variable ‘vSum’ returned

What is the best way to return a variable without it going out of scope? Also, how come we can return integers, floats, etc. without having to worry about this?

Upvotes: 2

Views: 109

Answers (1)

Christian Ternus
Christian Ternus

Reputation: 8492

The key is in your method signature:

TIntV& FindSum(const TIntV& v1, const TIntV& v2)

This says "I'm returning a reference to a TIntV."

Change it to

TIntV FindSum(const TIntV& v1, const TIntV& v2)

and you should be fine.

Upvotes: 4

Related Questions