矢量迭代器不是dereferencable

Poo*_*rna 9 c++ stl

我有一个名为Shape的抽象基类,从中派生出Circle和Rectangle,但是当我在VS 2005中执行以下代码时,我得到错误Debug assertion failed.同时我没有在任何类中重载==运算符

表达式:向量迭代器不可解除引用,这是什么原因.

  vector<Shape*> s1;
  s1.push_back(new Circle(point(1,2),3));
  s1.push_back(new Circle(point(4,3),5));
  s1.push_back(new Rectangle(point(1,1),4,5));

  vector<Shape*> s2(s1);
  reverse(s1.begin(),s1.end());

  (*find(s1.begin(),s1.end(),new Circle(point(1,2),3)))->move(point(10,20));
Run Code Online (Sandbox Code Playgroud)

Dav*_*rre 12

简单:

  • 查找失败,因为在比较Shape*的向量中找不到新创建的Circle
  • 失败的查找返回结束迭代器,它不是由调试断言捕获的可引用的

为了让它像你想要的那样工作,你需要比较Shape,而不是Shape*

正如其他答案所指出的,boost :: ptr_vector是实现这一目标的简单方法.


xto*_*ofl 6

就像@David Pierre建议的那样:find是基于值的:它在一个指针的迭代器范围内查找(例如0x0F234420),它等于new Circle(point(1,2),3)你刚才创建的指针.由于这是一个新对象,它不会存在.

您可以通过使用find_if比较指针引用的对象的运算符来解决这个问题.

但是,Criterium应该能够区分形状类型.

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<const Circle*>( 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<const Rectangle*>( pOther );
        if( pOtherR == NULL ) return false;
        // compare rectangle members
    }
};



Shape* pFindThis = new Circle(point(1,2),3);
vector<Shape*>::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));
}
Run Code Online (Sandbox Code Playgroud)