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

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

本文关键字:对象引用 返回 函数 c++ 为什么 内部      更新时间:2023-10-16

以下是网站上的一个示例:http://www.cplusplus.com/doc/tutorial/classes2/我知道这是一个行之有效的例子。然而,我不明白为什么对象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;
}

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

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

CVector CVector::operator+ (CVector param) {

这一行表示返回CVector的独立副本(对象引用看起来像CVector& ...(,因此

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

当这个返回时,外部作用域得到一个全新的临时副本。所以是的,临时已经不在我们身边了,但外部作用域将收到一个副本。

您按值返回它,因此它将在temp被销毁之前被复制。

编译器优化后,将在返回的地址上创建对象。临时对象不会在堆栈上创建->然后复制到返回地址->然后将其销毁。

它由值返回
这意味着从temp生成一个值的副本并返回。

要通过引用返回对象,您必须具有&在返回值签名中。