(继承)类指针存入vector后内存清除问题
class Shape
{
public:
int a;
Shape();
virtual ~Shape() {}
virtual void read() = 0 ;
};
class Point:public Shape
{
public:
int b;
Point() ;
~Point() {}
void read(ifstream& in);
};
class Line:public Shape
{
public:
int c;
Line() ;
~Line() {}
void read(ifstream& in);
};
//*******************************************
vector <Shape*> Shape;
//----读取,存入vector------
while(!in.eof())
{
in> > type;
switch(type)
{
case 1:
{Point* ppoint = new Point ;
ppoint-> read( in ) ;
Shape.push_back(ppoint) ;}
break;
case 2:
{Line* pline = new Line ;
pline-> read( in) ;
Shape.push_back(pline) ;}
break;
}
}
//-------------delete vector------------
vector <Shape*> ::iterator it;
for(it = Shape.begin(); it != Shape.end(); ++it)
{
if(Point* ppoint = dynamic_cast <Point*> (*it))
{
delete dynamic_cast <Point*> (*it);
//还是直接delete (*it);??
}
else if(Line* pline = dynamic_cast <Line*> (*it) )
{
delete dynamic_cast <Line*> (*it);
}
}
Shape.clear();
//--------------无论上面哪种delete都有问题---------------
77F9193C CC int 3
HEAP[×.exe]: Invalid Address specified to RtlFreeHeap( 2270000, 1974e28 )
[解决办法]
delete (*it),delete ppoint/pline应该都行,不知道你的问题在哪里。:(
[解决办法]
代码贴的全点,整理整理
[解决办法]
你delete了*it,但没有从vector里erase掉这个it所指元素呀。
[解决办法]
帮你试过了,问题跟vector无关,应该是别处的。
还有,代码中问题很多,这是伪码吗?比如:
vector <Shape*> Shape;
——变量名怎么类名重复?
[解决办法]
贴全代码。
[解决办法]
if(Point* ppoint = dynamic_cast <Point*> (*it))这句存在问题
[解决办法]
那句我觉得没问题,赋值顺便判断而已。
[解决办法]
理论上没有问题,但是在本题的实际操作中有问题
目的是为了删除vector的元素,何必再转来转去,直接在vector里删除不就可以了么
[解决办法]
for(it = Shap.begin(); it != Shap.end(); ++it)
{
delete (*it);
*it=NULL;
}
直接delete就不会出现所说的问题了