从 c++ 中的函数返回局部变量

Returning local variable from a function in c++?

本文关键字:返回 局部变量 函数 c++      更新时间:2023-10-16

这是摘自一个 c++ 教程:

// 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);
}
int main () {
  CVector a (3,1);
  CVector b (1,2);
  CVector c;
  c = a + b;
  cout << c.x << "," << c.y;
  return 0;
}

在运算符重载函数中,它创建一个本地var temp然后返回它,我很困惑,这是正确的方法吗?

"

这是正确的方法吗?"

是的,它是。请注意,它不是局部变量,而是实际返回的局部变量的副本,这是完全有效且正确的做法。在按指针或引用返回时返回局部变量时要小心,而不是在按值返回时返回。

是的

,因为它是按值返回的。如果函数具有以下签名,则不正确:

CVector& CVector::operator+(CVector param);

顺便说一下,更有效的实现如下所示:

CVector CVector::operator+(const CVector &param) const;