析构函数之前有效。怎么样?

时间:2011-08-22 10:13:19

标签: c++ visual-c++ destructor

#include<iostream>

using namespace std;
class test
{
int a;
public:
test()
{
    a=0;
}
test operator ++(int)
{        a++;
    return *this;
}
void display()
{
    cout<<a;
}
~test() {
    cout << "DES" << endl;
}
  };
int main()
{
    test t,t1;
    t1 = t++;
    t.display();
    system("pause");
}

我得到的输出是:

DES
1Press any key to continue...
DES 
DES

为什么析构函数以前会工作?

6 个答案:

答案 0 :(得分:8)

表达式t++会生成test类型的临时对象,因为operator++(int)会返回值[*]。在operator=使用它来分配t1的新值后,您会看到该临时性的破坏。

[*]通常这应该在递增之前包含t的值,但在您的实现中,它只是递增后的对象的副本,您可以通过执行return *this;来创建。所以你的函数体更适合operator++()(预增量)而不是operator++(int)(后增量)。

答案 1 :(得分:5)

因为

t1 = t++;

创建一个临时对象,该对象将在表达式(;)的末尾被销毁。

答案 2 :(得分:4)

当您使用t++时,会创建一个临时对象。这就是你有3个析构函数需要2个变量的原因。如果使用++t,则不会创建临时对象。除了运算符优先级之外,这是增量前和后增量之间的主要区别。

答案 3 :(得分:1)

原因是

test operator ++(int)
{
    a++;
    return *this;
}

返回一次立即销毁的临时对象

t1 = t++;
执行

是在调用system()之前执行的。

答案 4 :(得分:1)

operator ++(int)按值返回,而不是引用。创建并销毁临时文件。

答案 5 :(得分:1)

如果您希望++的行为与内置类型相同,那么:

  • preincrement(++t)应该递增,然后返回新值(可以通过引用返回);
  • postincrement(t++)应复制原始值,并在递增后返回。

你的后增量混合了两者;它递增,然后返回新值的副本(即行为像preincrement,但有不必要的副本)。当临时副本在创建完整表达式的末尾被销毁时,您将看到额外的析构函数调用。

更典型的实现如下:

test & operator++() {
    ++a;
    return *this;
}
test operator++(int) {
    test copy = *this;
    ++a;
    return copy;
}