Vector iterator not dereferencable

前端 未结 3 894
没有蜡笔的小新
没有蜡笔的小新 2021-01-02 09:27

I have an abstract base class called Shape from which both Circle and Rectangle are derived, but when I execute the following code in VS 2005 I get the error Debug assertion

3条回答
  •  攒了一身酷
    2021-01-02 10:13

    Like @David Pierre suggests: find is value-based: it looks in the range of iterators for a pointer (e.g. 0x0F234420) that equals the pointer to the new Circle(point(1,2),3) you just created. Since that's a new object, it won't be there.

    You can get around this by using find_if with an operator that compares the objects referenced to by the pointer.

    However, the Criterium should be able to differentiate between shape types.

    class Shape {
    public:
        //amongst other functions
        virtual bool equal( const Shape* ) const = 0;
    };
    
    class Circle : public Shape {
    public:
        bool equal( const Shape* pOther ) const {
            const Circle* pOtherCircle = dynamic_cast( pOther );
            if( pOtherCircle == NULL ) return false;
            // compare circle members
        }
    };
    
    class Rectangle : public Shape {
    public:
        bool equal( const Shape* pOther ) const {
            const Rectangle* pOtherR = dynamic_cast( pOther );
            if( pOtherR == NULL ) return false;
            // compare rectangle members
        }
    };
    
    
    
    Shape* pFindThis = new Circle(point(1,2),3);
    vector::const_iterator itFound = find_if(s1.begin(),s1.end(), 
        bind1st( mem_fun( &Shape::equal ), pFindThis) ) );
    delete pFindThis; //leak resolved by Mark Ransom - tx!
    
    if( itFound != s1.end() ) {
        (*itFound)->move(point(10,20));
    }
    

提交回复
热议问题