为什么在c++中的函数内部返回对象引用是可以的
Why is it OK to return an object reference inside a function in c++?
以下是网站上的一个示例: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生成一个值的副本并返回。
要通过引用返回对象,您必须具有&在返回值签名中。
相关文章:
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 如何通过引用返回对象
- C++对象引用返回不同的值
- 对象引用中的字段以不同的方法返回不同的值
- C++当您取消引用指向类对象的指针,然后将其作为引用返回时,是否可以对此引用调用方法
- 通过引用返回包含对象的向量
- 从函数返回 libconfig 类设置对象引用
- 在这种情况下,为什么使用 *此必需的对象引用返回对象引用
- 我应该返回引用堆对象还是返回值
- 通过引用返回共享对象是否安全"std::lock_guard<mutex>"?
- 通过值或通过引用返回类对象,这在这里会更快
- C++OOP基础知识-是否正确返回对象引用
- 创建返回对象引用的成员函数的最简单方法
- 如何实现一个创建新对象并返回对它的引用的C++方法
- 当你通过引用返回对象时,你什么时候需要担心对象会被破坏
- 为什么有些类方法返回"*this"(self的对象引用)?
- 在C++中返回伪对象引用的规则
- 通过引用返回/传递动态分配的对象
- jsoncpp:按名称访问JSON对象,返回可变引用,如果未找到则不创建对象
- 视觉对象 按引用返回,按值返回.C++