vector压入对象指针(A *)时, 内存不会托管,若对象A在堆上申请空间,需要手动delete ,避免内存泄露
1 错误使用情况, 没有析构A
class A
{
public:
A()
{
cout<<"A():"<<this<<endl;
}
A(int i):_data(i)
{
cout<<"A(i):"<<this<<endl;
}
A(const A & other)
{
cout<<"const A & other : "<<this<<" from "<<&other<<endl;
}
A& operator=(const A & other)
{
cout<<"operator= : "<<this<<" from "<<&other<<endl;
}
~A()
{
cout<<"~A(): "<<this<<endl;
}
private:
int _data;
};
int main()
{
vector <A *> res;
res.reserve(5);
res.push_back(new A);
return 0;
}
运行结果:
A():0x781158
2 正确使用
int main()
{
vector <A *> res;
res.reserve(5);
A *pa = new A;
res.push_back(pa);
delete pa;
return 0;
}
运行结果:
A():0x781158
~A(): 0x781158
2860

被折叠的 条评论
为什么被折叠?



