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++

          主站蜘蛛池模板: 阳曲县| 南投市| 延寿县| 白银市| 淮北市| 大埔区| 年辖:市辖区| 锡林郭勒盟| 蒙自县| 义乌市| 嵩明县| 泾阳县| 称多县| 台湾省| 盐山县| 阿拉尔市| 肥乡县| 青河县| 南漳县| 越西县| 蚌埠市| 耿马| 从化市| 安国市| 灵台县| 醴陵市| 康平县| 大荔县| 长治市| 商洛市| 沧州市| 洛阳市| 东乌| 宁波市| 临桂县| 青铜峡市| 昂仁县| 称多县| 额敏县| 泽库县| 莎车县|