so true

          心懷未來,開創未來!
          隨筆 - 160, 文章 - 0, 評論 - 40, 引用 - 0
          數據加載中……

          C++中臨時變量的優化與產生!

          #include <iostream>
          using namespace std;

          class A{
          public:
           A(){
            cout<<"ctor"<<endl;
           }
           ~A(){
            cout<<"dtor x="<<x<<endl;
           }
           void operator =(A a){
            cout<<a.x<<" wokao"<<endl;
           }
           int x;
          };

          A func(A a){
           return a;
          }

          void main(){
           A a1;
           a1=func(A());
          }
          輸出結果:
          ctor
          ctor
          dtor x=-858993460
          -858993460 wokao
          dtor x=-858993460
          dtor x=-858993460
          dtor x=-858993460
          dtor x=-858993460
          Press any key to continue

          ======================================
          為類A添加一個拷貝構造函數后:
          #include <iostream>
          using namespace std;

          class A{
          public:
           A(){
            cout<<"ctor"<<endl;
           }
           A(A& a){
            cout<<"copy ctor"<<endl;
           }
           ~A(){
            cout<<"dtor x="<<x<<endl;
           }
           void operator =(A a){
            cout<<a.x<<" wokao"<<endl;
           }
           int x;
          };

          A func(A a){
           return a;
          }

          void main(){
           A a1;
           a1=func(A());
          }

          運行結果:
          ctor
          ctor
          copy ctor
          dtor x=4856604
          4856604 wokao
          dtor x=4856604
          dtor x=-858993460
          Press any key to continue

          ==================================
          結論:
          就像C++ Primer中寫到的一樣,如果你不顯示提供一個copy ctor,那么編譯器使用bitwise copy完成copy ctor功能,由于該操作極為簡便,因此編譯器不會進行優化,需要的時候就進行此操作,因此第一段代碼的運行結果是調用了3次copy ctor。
          如果你自己定義了copy ctor,編譯器會認為:我的用戶自己定制了copy ctor,八成要做什么復雜工作吧,每次copy出一個對象來都得費不少事,那么我還是為他/她進行優化吧。因此第二段代碼僅僅調用了1次copy ctor。

          P.S.:測試環境是VC6,如果改用G++編譯器的話,我試驗了一下,結論就不像前述所說的那樣了,各個編譯器有各自的優化策略,總之。

          但VC6里面較好的體現出了Lippman的思想。

          posted on 2008-12-15 22:59 so true 閱讀(492) 評論(0)  編輯  收藏 所屬分類: C&C++

          主站蜘蛛池模板: 丘北县| 阿拉善右旗| 南部县| 金门县| 遂昌县| 张掖市| 固阳县| 临清市| 和平县| 佛教| 玛多县| 庄浪县| 渝中区| 安宁市| 昭觉县| 贺州市| 辰溪县| 义乌市| 山东| 伊川县| 新平| 江津市| 河西区| 绥德县| 宜黄县| 新宾| 江城| 清流县| 津市市| 邯郸县| 盱眙县| 吴忠市| 辽宁省| 黄陵县| 赤城县| 太和县| 邓州市| 定陶县| 赤壁市| 金溪县| 平潭县|