Why is it OK to return an object reference inside

2019-07-02 12:44发布

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

5条回答
地球回转人心会变
2楼-- · 2019-07-02 13:06

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.

查看更多
劳资没心,怎么记你
3楼-- · 2019-07-02 13:11

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.

查看更多
SAY GOODBYE
4楼-- · 2019-07-02 13:12
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.

查看更多
Melony?
5楼-- · 2019-07-02 13:18

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

查看更多
走好不送
6楼-- · 2019-07-02 13:20

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.

查看更多
登录 后发表回答