c++ - 使用新值而不是实际值的 C++ 类析构函数
问题描述
为什么这会在它破坏之前设置值而不是破坏类先前的值(5)?
#include <string>
#include <stdio.h>
class TestClass {
public:
int intval = 0;
TestClass(int pos) {
intval = pos;
}
~TestClass() {
printf("Deleted! %i\n",intval);
}
};
int main()
{
TestClass a(5);
a = TestClass(234);//should print out "Deleted! 5"
printf("Test\n");
}
输出:
Deleted! 234
Test
Deleted! 234
解决方案
在显示的代码中,您创建了两个对象,它们都被破坏了,但在不同的时间。
首先你有
TestClass a(5);
该对象a
将一直存在,直到作用域结束(这发生在函数的末尾)。这是您看到的第二个输出。Deleted! 234
你创建的第二个对象是当你做的时候
a = TestClass(234);
这里发生的是TestClass(234)
创建一个临时对象。这个临时对象用于复制赋值给a
,然后临时对象被破坏。这种破坏是您看到的第一个输出。Deleted! 234
解释
a = TestClass(234);
多一点,它大致相当于
{
TestClass temporary_object(234);
a.operator=(temporary_object);
// temporary_object ends its life here and the destructor will be called
}
完整的代码,带有创建和销毁对象的注释
int main()
{
TestClass a(5); // Create object a
a = TestClass(234); // Create temporary object, temporary object is destructed
printf("Test\n");
// As scope ends, the life-time of object a also ends, and a is destructed
}
推荐阅读
- php - 在两个 php 文件之间传递 csv 文件
- python - 我可以在 matplotlib 中使绘图的轴限制交互吗?
- java - 错误:(dberror) 268 - 列定义不明确:ROLLNO: line 1 col 7 (at pos 7)
- swift - 在 swift 4.0 中添加多个相同的 SKSpriteNode()
- logging - AWS lambda:如果 log4j.xml 中不存在环境变量,有没有办法设置默认值?
- java - 从具有列表作为数据字段的对象列表中显示 TableView 中的所有项目(JavaFX、TableView、FXML)
- reactjs - 使用 React 上传多张图片
- widget - 使用输入小部件进行计算,Bonitasoft
- flask - AttributeError:“NoneType”对象没有 Flask 上传的“文件名”属性
- python - 如何修复:“re.error:在 23457 位置没有重复内容”?