2012-09-11 30 views
-1

我只是在Widget中寫了一個簡單的operator =,但是當我操作符=它時,它會在vs2010中引發一個未處理的異常。 我在這些代碼中看不到任何錯誤。需要一些幫助。爲什麼operator =引發未處理的異常?

class WidgetImpl 
    { 
     public: 
      WidgetImpl (int _a, int _b, int _c) : 
       a_ (_a), b_ (_b), c_ (_c) 
      { 
      }; 
      //WidgetImpl& operator= (const WidgetImpl& rhs) { //if I define this function,everything will be allright. 

      // if (this == &rhs) { return *this; } 
      //// 
      ////.... do something 

      //// 
      //return *this; 
      // } 

      int a_, b_, c_; 
      std::vector<double> vector_; 
    }; 


    class Widget 
    { 
     public: 
      Widget() : pImpl_ (NULL) {}; 
      Widget (const Widget& rhs) {}; 
      Widget& operator= (const Widget& rhs) 
      { 
       if (this == &rhs) { return *this; } 

       *pImpl_ = * (rhs.pImpl_); 
       return (*this); 
      } 
      void SetImp (WidgetImpl* _Impl) 
      { 
       this->pImpl_ = _Impl; 
      } 

      WidgetImpl* pImpl_; 
    }; 

    int main (int argc, char** argv) 
    { 
     Widget w; 
     WidgetImpl* wimpl = new WidgetImpl (1, 2, 3); 
     w.SetImp (wimpl); 
     Widget w2; 
     w2 = w; //Unhandled exception throws here 

     return 0; 
    } 

正如你可以看到above.If我定義operator =類WidgetImpl。看起來一切正常..怪異的..

+0

確認GCC(段錯誤) – Kos

回答

4

您的w2pImpl_爲空,因此分配給它會導致未定義的行爲(通常是分段衝突)。

在在LHS代碼

  *pImpl_ = * (rhs.pImpl_); 

pImpl_爲空。

+0

這就是它!非常感謝你! –

相關問題