#include <iostream>
using namespace std;
struct A
{
A() { cout << "A()" << endl; }
//A( const A& ) { cout << "A(A)" << endl ;}
A& operator=( const A& ) { cout << "A=A" << endl; }
~A() { cout << "~A()" << endl; }
};
A foo( A a )
{
cout << "---" << endl;
return a;
}
int main(void)
{
{
foo( A() );
}
system( "pause" );
return 0 ;
}
在 VC++2005 下輸出為:
A()
---
~A()
~A()
~A()
為什麼 return a; 會調用2次析構函數?
---------------------------------- 簡化一下----------------------------------
#include <iostream>
using namespace std;
struct A
{
A() { cout << "A()" << endl; }
//A( const A& ) { cout << "A(A)" << endl ;}
A& operator=( const A& ) { cout << "A=A" << endl; }
~A() { cout << "~A()" << endl; }
};
void foo( A a )
{
}
int main(void)
{
{
foo( A() );
}
system( "pause" );
return 0 ;
}
VS2005中的怪異現象描述:
如果沒有 A( const A& ) { cout << "A(A)" << endl ;}
那麼輸出
A()
~A()
~A()
如果加上 A( const A& ) { cout << "A(A)" << endl ;}
那麼輸出
A()
~A()