Vector iterator not dereferencable

前端 未结 3 892
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-02 10:07

    This is a good reason to use boost::ptr_vector.

    It not only handles the fact that your objects need to be destroyed.
    xtofl@: You forgot the virtual destructor.

    But it also makes the members look like objects by returning references rather than pointers. This allows you to use the standard algorithms much more naturally rather than playing around with pointers in your 'equal' function (which is very un C++ like).

    #include 
    #include 
    
    class Shape
    {
        public:
            ~Shape()    {}
            bool operator==(Shape const& rhs) const
            {
                if (typeid(*this) != typeid(rhs))
                {
                    return false;
                }
    
                return this->isEqual(rhs);
            }
        private:
            virtual bool isEqual(Shape const& rhs) const    = 0;
    };
    
    class Circle: public Shape
    {
        public:
            Circle(int r)
                :radius(r)
            {}
        private:
            virtual bool isEqual(Shape const& r) const
            {
                Circle const&   rhs = dynamic_cast(r);
                return radius == rhs.radius;
            }
            int radius;
    };
    class Rectangle: public Shape
    {
        public:
            Rectangle(int h,int w)
                :height(h)
                ,width(w)
            {}
        private:
            virtual bool isEqual(Shape const& r) const
            {
                Rectangle   const&  rhs = dynamic_cast(r);
                 return (height == rhs.height) && (width == rhs.width);
            }
            int height;
            int width;
    };
    
    
    int main()
    {
    
        boost::ptr_vector    data;
    
        data.push_back(new Circle(5));
        data.push_back(new Circle(6));
        data.push_back(new Rectangle(7,4));
    
        boost::ptr_vector::iterator f;
        f = find(data.begin(),data.end(),Circle(6));
    
        std::cout << "Find(" << (f - data.begin() ) << ")" << std::endl;
    
    
    }
    

提交回复
热议问题