【问题标题】:Why is it OK to return an object reference inside a function in c++?为什么可以在 c++ 中的函数内返回对象引用?
【发布时间】:2011-07-02 10:21:34
【问题描述】:

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

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

【问题讨论】:

    标签: c++ reference overloading operator-keyword


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:
      CVector CVector::operator+ (CVector param) {
      

      这行说返回一个 CVector 的独立副本(对象引用看起来像 CVector&amp; ...),所以

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

      当它返回时,外部作用域会获得一个全新的 temp 副本。所以是的 temp 不再与我们同在,但外部范围将收到一份副本。

      【讨论】:

        【解决方案3】:

        你按值返回它,所以它会在temp被销毁之前被复制。

        【讨论】:

          【解决方案4】:

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

          【讨论】:

          • 我会避免谈论潜在的优化,重点是语义对象被复制到返回值之前函数完成(在return 声明)。该副本是否被优化是一个实现细节。
          【解决方案5】:

          按值返回。
          这意味着从 temp 复制值并返回。

          要通过引用返回对象,您必须在返回值签名中包含 &

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-11-11
            • 2020-07-25
            • 2019-05-05
            • 1970-01-01
            • 1970-01-01
            • 2020-03-12
            • 2017-04-18
            • 2015-07-22
            相关资源
            最近更新 更多