歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux綜合 >> Linux資訊 >> 更多Linux >> 如何得到constructor 和 copy constructor 執行次數

如何得到constructor 和 copy constructor 執行次數

日期:2017/2/27 14:17:58   编辑:更多Linux
  我們知道,編譯器在構造一個對象的時候,需要調用 constrUCtor,如果程序員本身沒有定義constructor,在某種狀況下則編譯器會給你合成一個,如果我們的對象具有了memberwise 語意的時候,則編譯器將會給你合成一個 operator= 和 copy constructor,編譯器會進行 data member 的 copy 操作,作為一些不太知道C++內部運作的程序員來說,如何知道copy constructor執行了幾次了呢? 不要企圖使用簡單的 int 來累加 constructor 和 copy constructor,如果 int 變量在類裡面,則在constructor的時候就構造了一次,destructor的時候就析構掉了,就無法得出正確的執行次數,或許你會說:我可以把 int 定義為全局變量啊,試試看,我們絕對無法得出一個對象調用了幾次constructor和copy constructor,而且數字出現偏差。 那該怎麼辦? 我們可以先定義一個簡單的類,裡面定義專有的操作,例如++操作符,和簡單的constructor, #include <iostream.h> struct C { int count; C():count(0) {} int operator++(int) { return count+=1; } // 重載++運算符 }; OK,定義好了這個基礎的 count 類之後,我們可以開始我們的constructor試驗。 我們首先定義一個叫 X 的類,裡面定義constructor和copy constructor,在裡面,利用前面定義的count類來進行累加數字: class X { friend class C; public: C ct; X():ct(*new C) { ct++;} // constructor,初始化 ct 並開始累加 X(const X &o) { ct = o.ct; ct++;} // copy constructor,將copy constructor 中 ct 的結果拷貝到 ct 中並累加 }; 我們開始吧 main() { X x; X a=x; X b=a; cout<<b.ct.count; /* 得到的這個數字就是對象 b 的 constructor 和 copy constructor 執行的次數 */ cout<<x.ct.count; /*就是對象 x 的constructor和copy constructor執行的次數*/ } 我們再來增加一點代碼,再做個試驗。 在 class X 後,我們再增加一個 X 的函數: X func(X &_this) { return _this; } 無疑,這個函數也會調用 copy constructor,那麼怎麼得到他的次數呢? main() { X x; X a=x; X b=a; int i = func(b).ct.count; cout<<i; /* 這個 i 就是用了 func 函數後得到的 constructor 和 copy constructor 執行的次數 */ } 有人要問,為什麼要寫 int i = func(b).ct.count; 而不直接寫:func(b).ct.count; ? 因為 func 是一個類型為 X 的函數,而這個函數是要調用 copy constructor 的,而這個調用是在 return _this 之後,所以如果直接寫:func(b).ct.count; 將會少一次累加,所以利用一個 int i 將得到完全執行完畢的 func 函數調用的 constructor 和 copy constructor。 在 X 類裡面,我們友元了類 C,C 的對象 ct 在 X 對象構造的時候初始化,然後開始累加,ct 的生命周期將保持到類 X 的結束。




Copyright © Linux教程網 All Rights Reserved