简体   繁体   中英

Why is it OK to return an object reference inside a function in c++?

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;
}

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.

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.

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM