临时对象在 C++ 中的行为方式?

How temporary objects behave in c++?

本文关键字:方式 C++ 临时对象      更新时间:2023-10-16

当我尝试运行下面的代码时,我完全困惑了。

#include<iostream>
using namespace std;
class test{
public:
int num = 30;
int yourAge ;
void set(){
yourAge = (test().num)*2; 
}
};
int main(){
test obj;

cout << test().yourAge << endl; // i was expecting garbage but giving me 0
cout << obj.yourAge << endl;    // ya! garbage it is, in this case
///// now/////
test().set()
cout << test().yourAge << endl;  // Iwas expecting 60 but giving me againg 0
cout << obj.yourAge << endl;  // I was expecting garbage but giving me 0;

return 0;
}

我已经在代码中描述了我的问题,但为什么它们会给出意想不到的结果。为什么会这样?是因为我正在使用临时无名对象还是发生了其他事情?我将感谢您的回答。

无论在何处使用test()生成一个类型test的临时对象,该对象按照类中的指定进行初始化。
此初始化对num成员30,但对yourAge成员可以是任何内容(静态存储除外,但这是另一个主题)。

然后,任何像test().yourAge这样的表达式都会构建一个临时对象,检索其值未初始化yourAge成员(可以是 -17、0 或其他什么),并让这个临时对象消失。

调用test().set()创建一个临时对象时,借助set()方法初始化其yourName成员,但让这个对象消失而不使用它!
任何后续test()表达式都是一个新的临时对象,没有理由与调用set()的对象相关联。

obj的情况类似,只是只要执行包含它的块(此处的main()函数),该对象就会持续存在。
它的yourAge成员永远不会初始化,所以它可以包含任何内容;如果你曾经使用过obj.set(),那么在那次调用之后,你可能会期望在obj.yourAge中找到相关的东西。