临时对象在 C++ 中的行为方式?
How temporary objects behave in c++?
当我尝试运行下面的代码时,我完全困惑了。
#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
中找到相关的东西。
相关文章:
- 如何在c++中为模板函数实例创建快捷方式
- 在c代码之间共享数据的最佳方式
- 在C++中将函数压缩为两种方式
- 以螺旋方式打印矩阵的程序.(工作不好)
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 创建引用向量的优雅方式
- Constexpr替代了新的放置方式,可以让内存中的对象保持未初始化状态
- 使用QQuickFramebufferObject时同步数据的最佳方式是什么
- 不同/较旧的处理器运行c++代码的方式是否不同
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 重载方法的方式会在使用临时调用时生成编译器错误
- 在reactor中存储eventHandlers的最佳方式是什么
- 如何以优化的方式同时迭代两个间距不相等的数组
- 以线程安全的方式调用"QQuickPaintedItem::updateImage(const QImage&image)"(no QThread)
- 为什么C++有不同的变量初始化方式?
- 在AVX通道中混洗的最佳方式
- 如何重新定义MPI_FLOAT,MPI_DOUBLE以 typedef 的方式
- 如何以静态代码分析友好的方式使用 #define 防护?
- 以迭代方式合并标准::unordered_map