Why is it OK to return an object reference inside

2019-07-02 13:24发布

问题:

Here is an example from website: http://www.cplusplus.com/doc/tutorial/classes2/ I know it is a working example. However, I don't understand why object temp can be returned from the operator+ overloading function. I have made some comments besides the codes.

// vectors: overloading operators example
#include <iostream>
using namespace std;

class CVector {
  public:
    int x,y;
    CVector () {};
    CVector (int,int);
    CVector operator + (CVector);
};

CVector::CVector (int a, int b) {
  x = a;
  y = b;
}

CVector CVector::operator+ (CVector param) {
  CVector temp;
  temp.x = x + param.x;
  temp.y = y + param.y;
  return (temp);   ***// Isn't object temp be destroyed after this function exits ?***
}

int main () {
  CVector a (3,1);
  CVector b (1,2);
  CVector c;
  c = a + b; ***// If object temp is destroyed, why does this assignment still work?***
  cout << c.x << "," << c.y;
  return 0;
}

回答1:

In your example you don't return an object reference, you simply return the object by value.

Object temp is in fact destroyed after the function exits but by that time its value is copied on the stack.



回答2:

CVector CVector::operator+ (CVector param) {

This line says return an independent copy of a CVector (an object reference would look like CVector& ...) , so

  CVector temp;
  temp.x = x + param.x;
  temp.y = y + param.y;
  return (temp);  

When this returns the outer scope gets a brand new copy of temp. So yes temp is no longer with us but the outer scope will have recieved a copy.



回答3:

You return it by value, so it will be copied before temp is destroyed.



回答4:

After compiler optimization, the object will be created on address where will be returned. The temporary object won't be created on the stack -> then copy to return address -> then destory it.



回答5:

It's returned by value.
This means a copy of the value is made from temp and returned.

To return an object by reference you would have to have a & in the return value signature.