#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");
}
The output that i get is :
DES
1开发者_如何学GoPress any key to continue...
DES
DES
Why does the destructor work before ?
The expression t++
results in a temporary object of type test
, since operator++(int)
returns by value[*]. You're seeing the destruction of that temporary, after operator=
has finished using it to assign the new value of t1
.
[*] Normally this should contain the value of t
prior to it being incremented, but in your implementation it's just a copy of the object after incrementing, which you create by doing return *this;
. So your function body is more suitable for operator++()
(pre-increment) rather than operator++(int)
(post-increment).
Because
t1 = t++;
creates a temporary object that will be destroyed by the end of the expression (;).
When you are using t++
a temporary object is created. This is the reason you have 3 destructors called for 2 variables. If you use ++t
, temporary object would not be created. Which, other than the operator precedence, is the main difference between pre- and post- incrementing.
The reason is
test operator ++(int)
{
a++;
return *this;
}
returns a temporary object that is destroyed immediately once
t1 = t++;
is executed which happens before the call to system()
.
operator ++(int)
returns by value, not reference. a temporary is created and destroyed.
If you want ++
to behave as it does for builtin types, then:
- preincrement (
++t
) should increment, then return the new value (which can be returned by reference); - postincrement (
t++
) should copy the original value, and return that after incrementing.
Your postincrement mixes both; it increments, then returns a copy of the new value, (i.e. acts like preincrement, but with an unnecessary copy). You are seeing the extra destructor call when that temporary copy is destroyed at the end of the full expression it was created in.
A more canonical implementation would look like:
test & operator++() {
++a;
return *this;
}
test operator++(int) {
test copy = *this;
++a;
return copy;
}
精彩评论