为什么operator=抛出未处理的异常

why operator= throws an Unhandled exception?

本文关键字:未处理 异常 operator 为什么      更新时间:2023-10-16

我只是在Widget中写了一个简单的operator=,但当我的operator=it时,它在vs2010中抛出了一个未处理的异常。我看不出这些代码有任何错误。需要一些帮助。

 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中定义运算符=。看起来一切都很好…奇怪。。

您的w2pImpl_为null,因此分配给它将导致未定义的行为(通常是分段冲突)。

在代码中

            *pImpl_ = * ( rhs.pImpl_ );   

LHS上的CCD_ 3为空。