1. 程式人生 > >沒想通的關於複製建構函式C++程式碼: A obj=func()

沒想通的關於複製建構函式C++程式碼: A obj=func()

class A
{
public:
    A(int x=0):i(x)
    {
        cout << "Normal Contructor: " << i << endl;
    }
    
    ~A()
    {
        cout << "Destructor: " << i << endl;
    }
    
    A(const A & x)
    {
        cout << "Copy Constructor: " << i << endl;
    }
    
    A 
& operator=(const A & x) { cout << "Operator = " << endl; return *this; } int i; }; A fun () { A t(2); return t; }
int main()
{
    A a(1);
    
    A b = fun();
    //fun();
    
    cout << "end of program" << endl;
    
    return 0;
}
 
  

  上面main()函式執行後的輸出為:

  Normal Contructor: 1
  Normal Contructor: 2
  end of program
  Destructor: 2
  Destructor: 1

int main()
{
    A a(1);
    
    //A b = fun();
    fun();
    
    cout << "end of program" << endl;
    
    return 0;
}
輸出為:

Normal Contructor: 1
Normal Contructor: 2
Destructor: 2
end of program
Destructor: 1