首页 > 解决方案 > 使用新值而不是实际值的 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

标签: c++

解决方案


在显示的代码中,您创建了两个对象,它们都被破坏了,但在不同的时间。

首先你有

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
}

推荐阅读