2012-09-11 2 views
-1

위젯에서 간단한 operator =를 쓰지만 operator = it 일 때 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; 
    } 

위에서 볼 수 있습니다. 연산자 =를 WidgetImpl 클래스에 정의하면 다음과 같습니다.

+0

GCC (segfault) – Kos

답변

4

w2pImpl_은 null이므로 할당하면 정의되지 않은 동작 (일반적으로 세그먼트 위반)이 발생합니다. 좌변의 코드

  *pImpl_ = * (rhs.pImpl_); 

pImpl_에서

널이다.

+0

에서 확인했습니다. 대단히 감사합니다! –

관련 문제