-1

I just write a simple operator= in Widget,but when I operator= it ,it throws an Unhandled exception in vs2010. I don`t see any wrong in these code. needs some help.

 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;
    }

As you can see above.If I define operator= in class WidgetImpl . It seems everything is OK.. weird..

4

1 に答える 1

4

w2'sはnullpImpl_であるため、これに割り当てると、未定義の動作(通常、セグメンテーション違反)が発生します。

コード内

            *pImpl_ = * ( rhs.pImpl_ );   

pImpl_LHSのはnullです。

于 2012-09-11T17:15:14.430 に答える