为什么在c ++中的函数内返回对象引用是可以的?

3 c++ overloading reference operator-keyword

以下是网站上的一个例子:http://www.cplusplus.com/doc/tutorial/classes2/ 我知道这是一个有效的例子.但是,我不明白为什么可以从operator +重载函数返回对象temp.除了代码之外,我已经做了一些评论.

// 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;
}
Run Code Online (Sandbox Code Playgroud)

Kar*_*ath 8

在您的示例中,您不返回对象引用,只需按值返回对象.

事实上,对象temp在函数退出后被销毁,但到那时它的值被复制到堆栈上.