繁体   English   中英

为什么可以在 c++ 的 function 中返回 object 引用?

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

这是来自网站的示例: http://www.cplusplus.com/doc/tutorial/classes2/我知道这是一个工作示例。 但是,我不明白为什么 object temp 可以从 operator+ 重载 function 返回。 除了代码之外,我还做了一些评论。

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

在您的示例中,您没有返回 object 引用,您只需按值返回 object 。

Object temp 实际上在 function 退出后被破坏,但到那时它的值被复制到堆栈上。

CVector CVector::operator+ (CVector param) {

此行表示返回 CVector 的独立副本(object 参考看起来像CVector&... ),所以

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

当这返回外部 scope 时,将获得一个全新的 temp 副本。 所以是的 temp 不再与我们同在,但外部 scope 将收到一份副本。

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

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

它是按值返回的。
这意味着该值的副本是从 temp 制作并返回的。

要通过引用返回 object,您必须在返回值签名中有&

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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