从 c++ 中的函数返回局部变量
Returning local variable from a function in c++?
这是摘自一个 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 ¶m) const;
相关文章:
- 返回对局部变量 - C++ 的引用
- libmysql:警告:返回局部变量"行"的地址(C++/C)
- 变量循环范围会导致返回局部变量的地址引用
- 通过引用返回局部变量
- C++ 返回局部变量或临时变量
- 警告:返回局部变量'buffer'地址
- 返回局部变量而不复制它们
- 警告:返回局部变量"角度"的地址 [-Wreturn-local-addr]
- 从 c++ 中的函数返回局部变量
- 返回局部变量C++的指针
- 我想返回局部变量的地址
- 通过复制返回局部变量 - 它是如何工作的
- 自动返回局部变量 x值
- 从lambda返回局部变量到const ref
- 在c++中返回局部变量(Effective c++第3版规则21)
- 转换谓词,通过引用返回局部变量
- C++中返回局部变量的引用和标准指针的替代方案是什么
- 返回局部变量
- C4172和C4239返回局部变量
- 为什么返回局部变量或临时变量的地址只是警告而不是错误?