拷貝建構函式在哪些地方用,函數參數,函數傳回值

來源:互聯網
上載者:User

首先看個程式。

#include <iostream>using namespace std;class A{public:A(){cout << "A"<<endl;}~A(){cout << "~A"<<endl;}private:int x;};void main(){A a;A b(a);A c(a);}

輸出結果是:

A
~A
~A
~A
請按任意鍵繼續. . .

 

=================================================

關於函數參數和函數傳回值的構造問題。

函數參數和傳回值的構造都是調用的拷貝建構函式。

並且在函數返回時都需要析構。

 

#include <iostream>using namespace std;class A{public:A(){cout << "A" <<endl;}~A(){cout << "~A" <<endl;}private:string x,y;};class B : public A{public:B(){cout << "B" <<endl;}~B(){cout << "~B" <<endl;}private:string x1,y1;};B fun(B b){return b;}void main(){B a,b;b = fun(a);}

輸出結果:

A
B
A
B
~B
~A
~B
~A
~B
~A
~B
~A
請按任意鍵繼續. . .

當把函數調用注釋掉後,輸出結果是:

A
B
A
B
~B
~A
~B
~A
請按任意鍵繼續. . .

 

可見相比fun函數的調用,只是多了兩次解構函式的調用而已。

 

#include <iostream>using namespace std;class A{public:A(){cout << "A" <<endl;}A(const A &a){cout << "construct A" <<endl;}~A(){cout << "~A" <<endl;}private:string x,y;};class B : public A{public:B(){cout << "B" <<endl;}B(const B &a){cout << "construct B" <<endl;}~B(){cout << "~B" <<endl;}private:string x1,y1;};B fun(B b){return b;}void main(){B a,b;b = fun(a);}

PS:調用拷貝建構函式之前會自動調用父類的建構函式

 A
B
A
B
A
construct B
A
construct B
~B
~A
~B
~A
~B
~A
~B
~A
請按任意鍵繼續. . .

 

//多餘調用的兩次解構函式。是函數參數和傳回值的析構。

//而函數參數和傳回值都是拷貝建構函式完成構造的。

//參考文獻:

//http://www.cnblogs.com/renyuan/archive/2012/12/29/2839230.html

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.